For Loop read different data from workspace

14 ビュー (過去 30 日間)
Alexander Epp
Alexander Epp 2018 年 7 月 25 日
回答済み: Alexander Epp 2018 年 7 月 25 日
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.

回答 (3 件)

Brett Bodamer
Brett Bodamer 2018 年 7 月 25 日
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 件のコメント
Alexander Epp
Alexander Epp 2018 年 7 月 25 日
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 2018 年 7 月 25 日
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'];

サインインしてコメントする。


Stephen23
Stephen23 2018 年 7 月 25 日
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 2018 年 7 月 25 日
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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by