MATLAB Answers

0

Replace Number array with characters

Asked by Mohit Garg on 17 Oct 2019
Latest activity Edited by Andrei Bobrov
on 18 Oct 2019
I have the following code:
function[]=fruit_find(volt)
fprintf("Voltage"+'\t\t'+"Fruit");
fprintf("\n------------------");
a=find(volt>=0 & volt<=10);
p=find(volt>10 & volt<=20);
g=find(volt>20 & volt<=30);
o=find(volt>30 & volt<=40);
u=find(volt>40 | volt<0);
m=[a,p,g,o,u]
m=sort(m);
fprintf("\n%.1f"+'\t\t\t\t'+"A",volt(a));
fprintf("\n%.1f"+'\t\t\t'+"P",volt(p));
fprintf("\n%.1f"+'\t\t\t'+"G",volt(g));
fprintf("\n%.1f"+'\t\t\t'+"O",volt(o));
fprintf("\n%.1f"+'\t\t\t'+"U",volt(u));
end
The output I need should look like this:
Voltage Fruit
---------------------------
18.0 P
33.0 O
31.0 O
34.0 O
15.0 P
37.0 O
10.5 P
48.0 U
50.0 U
38.0 O
...
So I was thinking of making a character array with the letters in the indexes of the numbers and printing them in fprintf, are their better ways to do this (without loops).
volt = [18 33 31 34 15 37 10.5 48 50 38 35 39 42 33 31 1 5 9 13 11 27 35 -1 46 22 6 19 36];
Thank you

  0 Comments

Sign in to comment.

Tags

Products


Release

R2019b

1 Answer

Answer by Andrei Bobrov
on 17 Oct 2019
Edited by Andrei Bobrov
on 18 Oct 2019

volt = [18 33 31 34 15 37 10.5 48 50 38 35 39 42 33 31 1 5 9 13 11 27 35 -1 46 22 6 19 36];
edges = [-inf,0:10:40,inf];
fruit = discretize(volt,edges,{'u','a','p','g','o','u'});
T = table(volt(:),fruit(:),'VariableNames',{'Voltage','Fruit'});

  2 Comments

Is there an easier way, with less complicated methods (that uses the find function as I have to use it)?
"Easier way" with find ! :)
edges = 0:10:40;
[~,i] = find(volt(:)' > edges(:));
ii = accumarray(i,1) + 1;
s = {'u','a','p','g','o','u'}';
T = table(volt(:),s(ii),'VariableNames',{'Voltage','Fruit'});
else "easier way" without find
i = sum(volt(:)' > edges(:)) + 1;
s = {'u','a','p','g','o','u'}';
T = table(volt(:),s(i),'VariableNames',{'Voltage','Fruit'});

Sign in to comment.