How can I fill an array with varying input dimensions and data type change?

조회 수: 1 (최근 30일)
Hello,
So I'm getting an input as an array of numbers:
Generator = [3111 3112 3112 3112].'
The last number of each row is asociated to a different number of variables with different names:
mod1 = {'\Delta \omega' '\Delta \delta'} % for 1
mod2 = {'\Delta\psi_g' '\Delta v_2' '\Delta G_t'} % for 2
I want to create a vector/ matrix which contains the set of variables, so i.e. 1 2 2 2:
v = ['\Delta \omega' '\Delta \delta' '\Delta\psi_g' '\Delta v_2' '\Delta G_t' '\Delta\psi_g' '\Delta v_2' '\Delta G_t' '\Delta\psi_g' '\Delta v_2' '\Delta G_t']
to then use them as indexing of the x-axis of a bar-plot.
The input from the generator might change, for each itteration I want to add more variables to my vector. How do I do this?
statevar = [].'
for i=1:length(Generator)
k= num2str(Generator(i))
j = str2num(k(4))
switch j
case 1
statevar(i) = 1 % =mod1 : how can I directly insert my variables names?
case 2
statevar(i) = 2 % =mod2 : how can I directly insert my variables names?
end
end

채택된 답변

Shubham Gupta
Shubham Gupta 2019년 8월 9일
Try this:
last_digit_vec = mod(Generator,10);
v = {};
for i = 1:length(Generator)
v = [v,eval(['mod',num2str(last_digit_vec(i))])];
end
Hope it helps !
  댓글 수: 2
Shubham Gupta
Shubham Gupta 2019년 8월 9일
There is one more efficient way that doesn't involve for loop :
master_mod = {mod1,mod2};
last_digit_vec = mod(Generator,10);
v = [master_mod{last_digit_vec}];
Both should give the same result.
Salome Hohl
Salome Hohl 2019년 8월 9일
Thanks a lot! Both a working perfectly!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by