Replace Number array with characters

2 Ansichten (letzte 30 Tage)
Mohit Garg
Mohit Garg am 17 Okt. 2019
Bearbeitet: Andrei Bobrov am 18 Okt. 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

Antworten (1)

Andrei Bobrov
Andrei Bobrov am 17 Okt. 2019
Bearbeitet: Andrei Bobrov am 18 Okt. 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 Kommentare
Mohit Garg
Mohit Garg am 18 Okt. 2019
Is there an easier way, with less complicated methods (that uses the find function as I have to use it)?
Andrei Bobrov
Andrei Bobrov am 18 Okt. 2019
Bearbeitet: Andrei Bobrov am 18 Okt. 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'});

Melden Sie sich an, um zu kommentieren.

Tags

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by