Use conditions on a matrix and manipulate the results

조회 수: 2 (최근 30일)
Zoltan
Zoltan 2014년 9월 29일
댓글: Star Strider 2014년 9월 29일
Hello,
I have a matrix:
a = [1 1 1 1; 0.99 1 1 1; 0.98 0.99 1 1; 0.97 0.99 0.99 0.99]
I would like to obtain the following result:
b = [0 0 0 0; 2 0 0 0; 0 3 0 0; 0 0 4 4]
It means that at the first time when 1 changes to 0.99 look up which row is it and write it in the 'b' matrix at the same place. If this condition is not true, write zero.
Thank you!

채택된 답변

Star Strider
Star Strider 2014년 9월 29일
This works:
a = [1 1 1 1; 0.99 1 1 1; 0.98 0.99 1 1; 0.97 0.99 0.99 0.99];
q1 = a(1:end-1,:) - a(2:end,:); % Subtract Rows From Offset Rows
q2 = a(2:end,:)==0.99; % Find Offset Rows = 0.99
q3 = [zeros(1,size(a,2)); q1 & q2]; % Create Logical Matrix (Cond 1 & Cond 2)
b = bsxfun(@times, q3, [1:size(a,1)]'); % Use ‘bsxfun’ To Number The Row Entries
  댓글 수: 2
Zoltan
Zoltan 2014년 9월 29일
Thank you very much, it works properly.
Star Strider
Star Strider 2014년 9월 29일
My pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by