Nested for loop still not working...

1 次查看(过去 30 天)
Why will this work...
if true
% code
end
InstNames = fieldnames(HistData);
HistData.(InstNames{1}).(DataNames{1}) = SepHistData(:,1,1);
HistData.(InstNames{1}).(DataNames{2}) = SepHistData(:,2,1);
HistData.(InstNames{1}).(DataNames{3}) = SepHistData(:,3,1);
HistData.(InstNames{1}).(DataNames{4}) = SepHistData(:,4,1);
HistData.(InstNames{1}).(DataNames{5}) = SepHistData(:,5,1);
HistData.(InstNames{1}).(DataNames{6}) = SepHistData(:,6,1);
HistData.(InstNames{1}).(DataNames{7}) = SepHistData(:,7,1);
HistData.(InstNames{2}).(DataNames{1}) = SepHistData(:,1,2);
HistData.(InstNames{2}).(DataNames{2}) = SepHistData(:,2,2);
HistData.(InstNames{2}).(DataNames{3}) = SepHistData(:,3,2);
HistData.(InstNames{2}).(DataNames{4}) = SepHistData(:,4,2);
HistData.(InstNames{2}).(DataNames{5}) = SepHistData(:,5,2);
HistData.(InstNames{2}).(DataNames{6}) = SepHistData(:,6,2);
HistData.(InstNames{2}).(DataNames{7}) = SepHistData(:,7,2);
and this won't...
if true
% code
end
for k = length(InstNames)
for i = length(DataNames)
HistData.(InstNames{k}).(DataNames{i}) = SepHistData(:,i,k);
end
end

采纳的回答

Paul
Paul 2014-2-18
编辑:Paul 2014-2-18
You should do
for k = 1:length(InstNames)
for i = 1:length(DataNames)
So add the 1:. This:
for k = length(InstNames)
assigns the value length(InstNames) to k without looping.
  1 个评论
Justin
Justin 2014-2-19
Thanks so much. These are the moments when one is reminded he's a beginner (I feel like exclaiming, DUH!).
Thanks, again.

请先登录,再进行评论。

更多回答(1 个)

Sean de Wolski
Sean de Wolski 2014-2-18
length(DataNames)
Will return something like seven I imagine.
Your for-loops will eventually want
SepHistData(7,7)
Which doesn't exist. This is not one of the options above
It seems to me like you want:
for k = 1:2
for i = 1:length(DataNames)
etc.
  1 个评论
Justin
Justin 2014-2-18
Sorry, that was a bad example, this is what I am really working with.
if true
% code
end
for k = length(InstNames)
for i = length(DataNames)
HistData.(InstNames{k}).(DataNames{i}) = SepHistData(:,i,k);
end
end
clearvars i k

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by