For Loop read different data from workspace

1 vue (au cours des 30 derniers jours)
Alexander Epp
Alexander Epp le 25 Juil 2018
Hey, so I am kind of new to matlab and got the following problem. I tried my best to find a solution at the internet but I guess I wasn't really able to adapt it to my problem.
I want to save different data in an array or cellarray like:
t{1} = str2double(ans.Configuration.CustomDefinitions.MyCellElement1_1.Soc.InitialCapacity.Text);
t{2} = str2double(ans.Configuration.CustomDefinitions.MyCellElement1_2.Soc.InitialCapacity.Text);
t{3} = ...
but with a for loop. The data in
ans.Configuration.CustomDefinitions.MyCellElement1_1.Soc.InitialCapacity.Text
is a datapath in my workspace, that leads to a string. I already tried different stuff like strcat(), but it didn't work.
Thanks in advance
Edit:
I want it to look like this:
for i=1:1:10
t{i} = str2double(ans.Configuration.CustomDefinitions.MyCellElement1_i.Soc.InitialCapacity.Text);
end;
But of course this would not work.

Réponses (3)

Brett Bodamer
Brett Bodamer le 25 Juil 2018
for i=1:length(t)
...
end
This should work. Put your assignment instruction inside of the for loop with i being your current index into the cell array.
  2 commentaires
Alexander Epp
Alexander Epp le 25 Juil 2018
t{1} = str2double(ans.Configuration.CustomDefinitions.MyCellElement1_1.Soc.InitialCapacity.Text);
t{2} = str2double(ans.Configuration.CustomDefinitions.MyCellElement1_2.Soc.InitialCapacity.Text);
Problem is i can't use the index i into the variable
for i=1:1:10
t{i} = str2double(ans.Configuration.CustomDefinitions.MyCellElement1_i.Soc.InitialCapacity.Text);
end;
This would not work. My question is how to use an index in a variable into function str2double. Sorry if my question wasn't clear enough.
Brett Bodamer
Brett Bodamer le 25 Juil 2018
Okay I see. I'm not sure how that long input is interpreted. But if it is a string, try concatenating the value of i into the string. It would look like this.
tempVar = ['1', num2str(2), '3'];

Connectez-vous pour commenter.


Stephen23
Stephen23 le 25 Juil 2018
Do NOT use ans as a variable name. I use S in my code below:
out = cell(1,10);
for k = 1:10
fld = sprintf('MyCellElement1_i.Soc',k);
str = S.Configuration.CustomDefinitions.(fld).InitialCapacity.Text;
out{k} = str2double(str);
end

Alexander Epp
Alexander Epp le 25 Juil 2018
That did the job
IniCap=zeros(40,1);
for cell_counter=1:40
IniCap(cell_counter) = str2double(ans.Configuration.CustomDefinitions.(['MyCellElement1_' num2str(cell_counter)]).Soc.InitialCapacity.Text);
end
Thanks

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by