Saving matrix data from nested for loop

7 visualizaciones (últimos 30 días)
DC
DC el 30 de Nov. de 2016
Comentada: DC el 1 de Dic. de 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

Respuesta aceptada

Jan
Jan el 30 de Nov. de 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 comentario
DC
DC el 1 de Dic. de 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...

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by