MATLAB Answers

0

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

Asked by Salome Hohl on 8 Aug 2019
Latest activity Commented on by Salome Hohl on 9 Aug 2019
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

  0 Comments

Sign in to comment.

1 Answer

Answer by Shubham Gupta on 9 Aug 2019
 Accepted Answer

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 Comments

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.
Thanks a lot! Both a working perfectly!

Sign in to comment.