Gamba Osaca
Gamba Osaca

Reputation: 307

how to do this in a for loop in Matlab

I have a 3-dimensial matrix W of size 160x170x18 and I want to compute the difference between each sucessive matrices inside W.

For example diff1 = W(:,:,1) - W(:,:,2) and diff2 = W(:,:,2) - W(:,:,3), etc ...

Next I want to select some special parts of the resulting matrices, For example:

NewDiff1 = [diff1(20:50,110:140); diff1(60:90,110:140)];

and the same thing for the other matrices. finally I want to compute the mean of each matrix and the error as follow:

mean1 = mean(mean(NewDiff1));
er1 = 0.1-abs(mean1);

I succeeded to do this for each matrix alone, but prefer to do all at once in a for loop.

Upvotes: 2

Views: 141

Answers (2)

High Performance Mark
High Performance Mark

Reputation: 78316

The expression

diff1 = diff(W,1,3)

will return, in your example, a 160*170*17 matrix where diffW(:,:,1) = W(:,:,2) - W(:,:,1), which isn't quite what you want. But

diff1 = (-1)*diff(W,1,3)

does, if my arithmetic is good, give you the differences you want. From there on you need something like:

newdiff1 = [diff1(20:50,110:140,:);diff1(60:90,110:140,:)];

and

means = mean(mean(newdiff1));
er1 = 0.1 - abs(mean1);

I haven't tested this thoroughly on matrices of the size you are working with, but it seems to work OK on smaller tests.

Upvotes: 4

ely
ely

Reputation: 77424

Store your matrices into a cell array and then just loop through the contents of the cell array and apply the same differencing logic to each thing. Be careful to use the {} syntax with a cell array to get its contents, rather than () which gives you the cell at a particular location.

Upvotes: 1

Related Questions