Nedimar
Nedimar

Reputation: 57

Loop over part of Matrix

I have a Matrix A. I want to iterate over the inner part of the matrix (B), while also working with the rows and columns that are not part of B.

A = [1 4 5 6 7 1;    B = [2 2 2 2;
     8 2 2 2 2 1;         2 3 3 2;
     9 2 3 3 2 1;         2 8 2 2];
     0 2 8 2 2 1;      
     1 1 1 1 1 1];    

I know it is possible to select the part of A like this:

[rows,columns] = size(A);
B = A([2:1:rows-1],[2:1:columns-1]);
for i = 1:(rows*columns)
    %do loop stuff
endfor

This however wont work because I also need the outer rows and columns for my calculations. How can I achieve a loop without altering A?

Upvotes: 0

Views: 177

Answers (1)

marolafm
marolafm

Reputation: 345

So, why do not use two indexes for the inner matrix?

%....
for i=2:rows-1
    for j=2:cols-1
        % here, A(i,j) are the B elements, but you
        % can still access to A(i-1, j+1) if you want.
    end
end
%....

Upvotes: 1

Related Questions