For Loop read different data from workspace

조회 수: 13 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by