How to compare each element of a matrix with a number? And then star it out

7 views (last 30 days)
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 Comments
Bob Thompson
Bob Thompson on 8 Feb 2019
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
Walter Roberson on 8 Feb 2019
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 .

Sign in to comment.

Answers (2)

Andrei Bobrov
Andrei Bobrov on 8 Feb 2019
a = [1 2 3 4 5 6 7]';
c = 6;
lo = a >= c;
z = ["","*"]';
out = a + z(lo+1);
  1 Comment
Walter Roberson
Walter Roberson on 8 Feb 2019
Note this requires R2017a or later; with a small modification it could be used with R2016b, but no earlier.

Sign in to comment.


Stephen23
Stephen23 on 8 Feb 2019
>> 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.

Community Treasure Hunt

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

Start Hunting!