user45919
user45919

Reputation: 75

How to loop through each value in a 3D matrix?

I have a matrix, 10x10x40, that is storing information of an image through time, where the the rows and columns indicate the spectral value at a specific point, and the third dimension is time. So in other words, a 10x10 image at 40 points in time. I would like to loop through each row, column and view that pixel history (1,1,:), (1,2,:)....(10,10,:).

Here's what I'm doing now:

val = [];
for i = 1:10;
  for j = 1:10;
    for k = 1:length(timevector)
      val(k) = my_matrix(i,j,k); 
    end
  end
end

Since I want to iterate through each pixel in time and then save that data, what would be the best way to store the new value/time vectors? I want to end up with 100 pixel history vectors, right now I end with one, and it's because val is written over within the loop. I know it's not advised to create variables within a loop, so what is the best alternative? Should I look into storing the output as a structure? I've been staring at this and I have over-complicated everything.

Upvotes: 0

Views: 687

Answers (2)

tryman
tryman

Reputation: 3293

Depending on the structure you prefer, you can also use matlab's functions reshape and num2cell to get the output in the following form:

Alternative 1:

A = reshape(A,[],10);

This will return a matrix (100x40) where each row is a pixel's history.

Alternative 2:

A = num2cell( reshape(A,[],40), 2)

This will return a cell array (100x1) where each cell contains a vector (40x1) with each pixel's history.

Alternative 3:

A = squeeze( num2cell( permute(A, [3,1,2]), 1) );

This will return a cell array (10x10) where each cell contains a vector (40x1) with each pixel's history.

Upvotes: 2

rinkert
rinkert

Reputation: 6863

Depending on what you want to do with it, you don't need to store them in separate vectors. You can just get one of these pixel history vectors, like so,

pixel_history = squeeze(my_matrix(1,1,:));

squeeze will remove the singleton dimension from the slice, and make it into a 40-by-1 vector, instead of a 1-by-1-by-40 matrix.

To make the time dimension the first matrix dimension, you could also permute the matrix,

permute(my_matrix, [3 2 1]);

This will swap the 3rd and 1st dimensions, making the 1st dimension time.

Upvotes: 2

Related Questions