Replace Number array with characters
21 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
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
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'});
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!