How to combine 2 for loops
42 次查看(过去 30 天)
显示 更早的评论
Hi, I have
id = [ 1 3; 2 6; 3 2; 4 5; 5 1; 6 4; 7 7];
I will get two new_ids by sorting its column,
for col=1:c
new_id{col}=sortrows(id,col);
end
I want to get 2 results from each of the new_id respectively. This means that I will have in total 4 results.
for m=1:2
result{m}=id(m:m+1,:);
end
How can i combine all this? Thank you.
3 个评论
采纳的回答
David Sanchez
2014-6-5
You were not very clear in your explanation, but I think you want this:
id = [ 1 3; 2 6; 3 2; 4 5; 5 1; 6 4; 7 7];
c=size(id,2);%I'm guessing c = Nº columns in id
result = cell(2); % pre-allocation of 2x2 cell array to hold data
for col=1:c% col=2
new_id{col}=sortrows(id,col);
for m=1:2% m=2
result{m,col}=new_id{col}(m:m+1,:);
end
end
You will end up with a cell array result whose columns contain the result of your first loop
2 个评论
David Sanchez
2014-6-5
I tested it in Matlab 2012a and it works. Try with a temporal variable in between
id = [ 1 3; 2 6; 3 2; 4 5; 5 1; 6 4; 7 7];
c=size(id,2);%I'm guessing c = Nº columns in id
result = cell(2); % pre-allocation of 2x2 cell array to hold data
for col=1:c% col=2
temp = sortrows(id,col);
new_id{col} = temp;
for m=1:2% m=2
result{m,col}=new_id{col}(m:m+1,:);
end
end
if it does not work, paste the error and the value of temp
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!