Replace Number array with characters
16 views (last 30 days)
Show older comments
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
Answers (1)
Andrei Bobrov
on 17 Oct 2019
Edited: 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
Andrei Bobrov
on 18 Oct 2019
Edited: Andrei Bobrov
on 18 Oct 2019
"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'});
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!