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

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Shubham Gupta
Shubham Gupta am 9 Aug. 2019
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 Kommentare
Shubham Gupta
Shubham Gupta am 9 Aug. 2019
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by