how to compare two consecutive values in a matrix

조회 수: 22 (최근 30일)
qing li
qing li 2022년 7월 29일
댓글: qing li 2022년 7월 31일
deal all,
how to compare two consecutive values in a matrix called 'temp' row-wise, the rule and the expecting result is as the following:
if first value>=second value , then bit=1;
else if first value<second value, then bit=0;
Store the bit generated every time in a matrix ‘M’.
This step will generate a matrix ‘M’ (logical) of size same a temp.
say for instance let's say matrix 'temp' be temp=[1,2,2,1;3,4,4,3;5,6,6,5;7,8,8,7]
can anyone give me some hints, thx a lot !

채택된 답변

Voss
Voss 2022년 7월 29일
temp=[1,2,2,1;3,4,4,3;5,6,6,5;7,8,8,7]
temp = 4×4
1 2 2 1 3 4 4 3 5 6 6 5 7 8 8 7
In each row, you have one fewer comparisons than you have elements, so M is of size one less than temp.
M = logical(temp(:,1:end-1) >= temp(:,2:end))
M = 4×3 logical array
0 1 1 0 1 1 0 1 1 0 1 1
Maybe you want to append a column of false values to M.
M(:,end+1) = false
M = 4×4 logical array
0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0
Another way to do the same:
temp2 = [temp NaN(size(temp,1),1)];
M = logical(temp2(:,1:end-1) >= temp2(:,2:end))
M = 4×4 logical array
0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0
  댓글 수: 5
Voss
Voss 2022년 7월 30일
In that case, you can do it like this:
temp=[1,2,2,1;3,4,4,3;5,6,6,5;7,8,8,7]
temp = 4×4
1 2 2 1 3 4 4 3 5 6 6 5 7 8 8 7
% make a row vector of the elements in temp in the proper order for the comparison
temp_row = reshape(temp.',1,[]);
% add the first element to the end for comparing the last and first elements
temp_row(end+1) = temp(1);
disp(temp_row)
1 2 2 1 3 4 4 3 5 6 6 5 7 8 8 7 1
% perform the comparison
M = temp_row(1:end-1) >= temp_row(2:end)
M = 1×16 logical array
0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1
% reshape the result back to the right size
M = reshape(M,size(temp,2),[]).'
M = 4×4 logical array
0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1
qing li
qing li 2022년 7월 31일
great that is what i want ! thank you sooo much sir ! that is really helpful !

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

추가 답변 (1개)

Matt J
Matt J 2022년 7월 29일
M=(diff(temp2,1,2)<=0);
  댓글 수: 1
qing li
qing li 2022년 7월 29일
thank you so much sir ! That is really helpful !

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by