How to combine 2 for loops

조회 수: 42 (최근 30일)
Grace
Grace 2014년 6월 5일
댓글: David Sanchez 2014년 6월 5일
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
Grace
Grace 2014년 6월 5일
For example,
id = [ 1 3; 2 6; 3 2; 4 5; 5 1; 6 4; 7 7];
for m=1:2
result{m}=id(m:m+1,:);
end
The code above gives me two sets of array,result{1} and result{2}. But now i sort my initial array which i denoted as "id" by sorting its column, and this will gives me two new_id, I sort it by following:
id = [ 1 3; 2 6; 3 2; 4 5; 5 1; 6 4; 7 7];
for col=1:c
new_id{col}=sortrows(id,col);
end
After that i want to run my first "for loop" to this two new_id by using the same code
for m=1:2
result{m}=id(m:m+1,:);
end
Means that i need to combine this two loops in order for me to do that. Do i make myself clear?
Grace
Grace 2014년 6월 5일
편집: Grace 2014년 6월 5일
Here is the code that I created:
id = [ 1 3; 2 6; 3 2; 4 5; 5 1; 6 4; 7 7];
[r c]=size{id);
for col=1:c
for m=1:2
new_id=sortrows(id,col);
result{m}=new_id(m:m+1,:);
end
end
My problem here is the output only shows me the loop when col=2, it overwrite the output for col=1, what can I do in order for me to keep both of the results for col=1 and 2?

댓글을 달려면 로그인하십시오.

채택된 답변

David Sanchez
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
Grace
Grace 2014년 6월 5일
Hi David,
I can't run the above code, it shows me
Cell contents assignment to a non-cell
array object.
Error in
new_id{col}=sortrows(id,col);
What is the problem?
David Sanchez
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 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