Numeric matrix to string matrix

조회 수: 5 (최근 30일)
Emmanuel Matata Bili Bili
Emmanuel Matata Bili Bili 2020년 3월 7일
댓글: Emmanuel Matata Bili Bili 2020년 3월 28일
Hi,
Newbie here, need some assistance in solving this problem.
Input is a numeric matrix x (any dimension). Return value is a string matrix.
The rules are :
If the x <= 30, then return “small”, if 30 < x <= 50, then return “medium”, otherwise return “high”
When I run the first "If" statement by itself I get x = "low" "low" "low" "low"
Then when I add the elseif statement I get nothing. Matlab simply ouputs the same results.
It seems like the code is only looking at the first row of my matrix. It also seems that it's considering 45 as less than 30.
I appreciate all the help in advance. I'm new learner, slowly learning programming.
First if statement only.
A = [1 2 45 4 ; 5 6 45 8];
for i = 1:length(A);
if A(i) <= 30
x(i)= "low"
end
end
>>
x =
1×4 string array
"low" "low" "low" "low"
elseif statement
A = [1 2 45 4 ; 5 6 45 8];
for i = 1:length(A);
if A(i) <= 30
x(i)= "low"
elseif 30 > A(i) & A(i)<= 50
x(i) = "medium"
end
end
>>
x =
1×4 string array
"low" "low" "low" "low"

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 3월 7일
편집: Ameer Hamza 2020년 3월 7일
x = [5 15 25;
35 45 55;
65 75 85];
result = strings(size(x));
result(x<=30) = "small";
result(x>30 & x<=50) = "medium";
result(x>50) = "large";
The result is
result =
3×3 string array
"small" "small" "small"
"medium" "medium" "large"
"large" "large" "large"
  댓글 수: 1
Emmanuel Matata Bili Bili
Emmanuel Matata Bili Bili 2020년 3월 28일
Hi - Ameer,
Thank you for your answer. I completely forgot to say thanks.
I appreciate the help. Thanks!!!!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2020년 3월 7일
The easiest way, by far, to do this in matlab is:
A = [1 2 45 4 ; 5 6 45 8]; %demo data
result = discretize(A, [-Inf, 30, 50, Inf], ["low", "medium", "high"])
  댓글 수: 1
Emmanuel Matata Bili Bili
Emmanuel Matata Bili Bili 2020년 3월 28일
Allo Guillaume,
Thanks for the answer!
I completely got sidetracked and excited about trying both solutions and I forgot to say thanks.
It all worked fine with your solution as well.
Thank you!!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by