Emily
Emily

Reputation: 539

How to store matrix in an array within a loop?

I'm developing an app in which I need to store matrix in an array within a loop, something like this:

MatTable=[];
for i=1:n 
Mat=binarisation(Images(i,:)); %binarisation returns a matrix (binary image)
MatTable=[MatTable, Mat];
end 

There is no error during execution of this code, but the result is not correct, I tried to display the content of MatTable using: display(MatTable(i));and the result is always: ans=1;

I guess this isn't the right way to store matrix in an array within a loop, so what is the correct way to realise it?

Upvotes: 0

Views: 100

Answers (1)

Adriaan
Adriaan

Reputation: 18177

What your code does, is grabbing an image and storing it side-by-side in a matrix. So what happens is that if your image is e.g. 10x10 pixels, and n=2, you'd get an 10x20 matrix.

I'd suggest a 3D array of storing things:

Images = rand(4);
n=3;
MatTable=[];
for ii = 1:n
    Mat = Images;
    MatTable(:,:,ii) = Mat;
end

which produces a 3D array MatTable, where each image is contained along the third dimension (so the third image would be MatTable(:,:,3)). This allows for easy access to all images through that third dimension, as opposed to keeping track of the width of images to find our where one ends and the next one starts.

I assume here all your images are the same size after your operation, which is not necessarily what you have, since your above code only requires the same amount of rows.

Upvotes: 1

Related Questions