syakey
syakey

Reputation: 41

MATLAB nested for loop to read variables to insert in equation

I have variables in Matlab workspace, which consists of coordinates of nonzero pixels of image.

Example

From that variable stored, i want to read row by column to define x1, x2, y1, y2 values so that i can apply to my equation.

For example on the first loop:

x1=127, y1=38
x2=128, y2=38

Second loop (which its stepsize is 1):

x1=128, y1=38
x2=129, y2=38

These are the code that i thought of but i know it won't work.

%r is for the row values, and c is for the column values.%
coordinates = [r, c];

%To define the size of my coordinates%
num_rows = size(coordinates,1);
num_cols = size(coordinates,2);

%To calculate the slopes using row-column values%
for x1 = 1:num_rows
    for y1 = 1:num_cols
        for x2 = 2:num_rows
            for y2 = 2:num_cols

                  %Calculate M%
                  M = (y2-y1)/(x2-x1);
                end
            end
        end
    end

How can i define the values x1,x2,y1,y2 by using nested for loop? so that i can use my x1,x2,y1,y2 in my equation slopes = (y2-y1)/(x2-x1).

Upvotes: 0

Views: 319

Answers (1)

articuno
articuno

Reputation: 556

From my understanding, your coordinates matrix will have only 2 columns where column 1 represents x coordinates and column 2 represents corresponding y coordinates. In that case you can find the slope matrix simply by-

coordinates = [r, c];
num_rows = size(coordinates,1);
shiftedCoordinates = coordinates(2:num_rows,:);
diffMat = shiftedCoordinates-coordinates(1:num_rows-1,:);
slopeMat = diffMat(:,2)./diffMat(:,1);

slopeMat is the matrix which you want (M)

Upvotes: 1

Related Questions