How to compare each element of a matrix with a number? And then star it out
조회 수: 3 (최근 30일)
이전 댓글 표시
I have a 23x1 matrix of numbers, and i want to compare with a single number to see if any of the numbers in the matrix are greater or equal than it. And if that is the case, then I want there to be a star (or something of that kinda) that is added beside that number so that i can easily recognize it when i print it to the command window.
For instance I have the matrix, [1 2 3 4 5 6 7]' and for instance, i want o campare it with 6, then i would like it to output [1 2 3 4 5 6* 7*]'
댓글 수: 4
Bob Thompson
2019년 2월 8일
Identifying the numbers numerically is rather easy.
A = rand(23,1);
check = 6;
B = A(A >= 6);
This returns an array, B, of the numbers greater than your check number. If you want to know where those numbers are then you can just use B = A>= 6; which generates a matrix of 1s and 0s where 1s indicate numbers that meet the condition.
Writing the output with stars would generally be an expansion of this type of check. Since all you want to do is print it to the command window I don't know that Walter's suggestion of a separate function is necessary, but I also don't use fuctions as often as I probably should.
str = '';
for i = 1:length(A);
if A(i) >= check
tmp = [num2str(A(i)),'* '];
else
tmp = [num2str(A(i)),' '];
end
str = [str tmp];
end
str
Walter Roberson
2019년 2월 8일
This is the kind of operation one does during debugging, so one would probably want to do this upon demand. It is easier to put it into aa function than to copy and paste the code every time one wants to execute it interactively .
답변 (2개)
Andrei Bobrov
2019년 2월 8일
a = [1 2 3 4 5 6 7]';
c = 6;
lo = a >= c;
z = ["","*"]';
out = a + z(lo+1);
댓글 수: 1
Walter Roberson
2019년 2월 8일
Note this requires R2017a or later; with a small modification it could be used with R2016b, but no earlier.
Stephen23
2019년 2월 8일
>> V = 1:7;
>> N = 6;
>> C = cellstr(num2str(V(:)))
>> X = V>=N;
>> C(X) = strcat(C(X),'*')
C =
'1'
'2'
'3'
'4'
'5'
'6*'
'7*'
Reshape and display as required.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!