Replace Number array with characters

21 ビュー (過去 30 日間)
Mohit Garg
Mohit Garg 2019 年 10 月 17 日
編集済み: Andrei Bobrov 2019 年 10 月 18 日
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

回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2019 年 10 月 17 日
編集済み: Andrei Bobrov 2019 年 10 月 18 日
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 件のコメント
Mohit Garg
Mohit Garg 2019 年 10 月 18 日
Is there an easier way, with less complicated methods (that uses the find function as I have to use it)?
Andrei Bobrov
Andrei Bobrov 2019 年 10 月 18 日
編集済み: Andrei Bobrov 2019 年 10 月 18 日
"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'});

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by