How to compare each element of a matrix with a number? And then star it out
15 次查看(过去 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!