Saving matrix data from nested for loop

조회 수: 2 (최근 30일)
DC
DC 2016년 11월 30일
댓글: DC 2016년 12월 1일
I have a 18624*3 matrix called 'vertices2' that I wish to break up into separate matrices of 24*3 e.g. rows 1-24, 25-48 and so on. I have the following code which loops through my matrix to (almost) do what I want but it has two problems:
[x,y] = size(vertices2);
for i = 1:24:x
for j = 1:3:y
vertices3(i,j) = vertices2(i:(i+23), j:(j+2));
end
end
As it stands I get the following error... 'Assignment has more non-singleton rhs dimensions than non-singleton subscripts'. This isn't an error message I'm used to getting from using for loops.
If I remove the (i,j) then the code works but as you'd expect, the loop only saves that last iteration of the loop e.g. data from rows 18601-18624, which is of no use to me!
I've tried a number of variations of the code to get it to run but I'm hitting a brick wall and was hoping someone could help! Maybe the step I'm missing is to save each iteration as a new matrix before the loop moves onto the next??
Thanks in advance

채택된 답변

Jan
Jan 2016년 11월 30일
The error message is as expected. With the debugger you can find out what happens in the first iteration:
for i = 1:24:x
for j = 1:3:y
vertices3(i,j) = vertices2(i:(i+23), j:(j+2));
==>
vertices3(1,1) = vertices2(1:24, 1:3);
Now you have a scalar on the left side and a matrix on the right side. This must fail. In the next iteration you would try to write "vertices(1,3)", but what should be in "vertices(1,2)"?
It is more efficient to use a 3D array to store the values:
vertices3 = reshape(vertices2, 24, [], 3);
Now the 2nd index means the specific block of data. Perhaps a permute is useful for resorting.
  댓글 수: 1
DC
DC 2016년 12월 1일
Hi Jan,
Thanks for both the help and explanation - makes perfect sense now. And vert = permute(vertices3,[1 3 2]); worked a treat! I was unaware of the permute command but looks like it's a good one to know. Now to crack on with the rest of my work...

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by