8 views (last 30 days)

Show older comments

I have the matrix (which is basically the matrix representation of several lines)

A = [10 5 10 % first two columns are the gradients in x-direction and the last column is the y-intercept

0 4 3

2 0 8

0 6 5];

I want to find the intersection between the lines starting from bottom going up (for each column seperately) when the gradients are non-zero, e.g., the last row of first column has zero gradient so I ignore it and move up to third row, but the second row has zero gradient as well, so I calculate its intersection with the first row:

The first row elements are always non-zero and since there is no "previous row" before the first row, the intersection of the those lines by default are set to zero. I have achieved my target using for loop, but I was hoping to avoid for loops if possible (I will have more columns than just 3). Here is what I have done:

for k = 1:2

B = A(A(1:end,k)~=0,[k,n]); % for each column, I am finding the matrix that does not include zero gradients

[r,~] = size(B);

c = 2:r;

if isempty(c)

x{k} = 0;

else

x{k} = [0; (B(c,end)-B(c-1,end))./(B(c-1,1)-B(c,1))];

end

end

which gives me my desired results:

>> x{1}

ans =

0

-0.2500

>> x{2}

ans =

0

-7

-1

Notice how the dimensions of x{1} and x{2} are different, and thus I had to use curly brackets. Avoiding the for loop can save me great deal of computational time. Thanks in advance! Let me know if you have any question.

Shojiro SHIBAYAMA
on 29 Jun 2020

Honestly, I didn't get what you want do precisely, but the following code may help you. IMO, for loop in MATLAB doesn't prolong the computation time.

dAn_p = A(2:end,:)-A(1:(end-1),:); % 'next' and 'previous' matrix from A.

tmp = cell2mat(arrayfun(@(ix)-dAn_p(:,end)./dAn_p(:,ix), 1:3,'un',0)); % take the gradient

tmp(A(2:end,:)==0|A(1:(end-1),:)==0)=0 % set elements zeros where any corresponding elements in A are zeros.

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!