Saving matrix data from nested for loop

2 views (last 30 days)
DC
DC on 30 Nov 2016
Commented: DC on 1 Dec 2016
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

Accepted Answer

Jan
Jan on 30 Nov 2016
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 Comment
DC
DC on 1 Dec 2016
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...

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!