Clear Filters
Clear Filters

Nested for loop still not working...

2 views (last 30 days)
Justin
Justin on 18 Feb 2014
Commented: Justin on 19 Feb 2014
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

Accepted Answer

Paul
Paul on 18 Feb 2014
Edited: Paul on 18 Feb 2014
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 Comment
Justin
Justin on 19 Feb 2014
Thanks so much. These are the moments when one is reminded he's a beginner (I feel like exclaiming, DUH!).
Thanks, again.

Sign in to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski on 18 Feb 2014
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 Comment
Justin
Justin on 18 Feb 2014
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

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!