Function - Input is a numeric vector x (any length). Return value is a list of string and matlab

Hi Matlab Community
I'm new to programming and I'm learning Matlab.
I'm trying to figure out this problem.
I need to create a function where the input is a numeric vector x (any length). Return value is a list of string.
If the x <= 30, then return “small”, if 30 < x <= 50, then return “medium”, otherwise return “high”
When I run the function I get vec = Small
Here is the function:
function x = numvec(v)
%x = []
for i =length(v);
if v(i) <= 30;
x = 'small';
elseif (30 < v(i)) & (v(i) <=50)
x = 'medium';
end
end
When I call the function.
v = [30, 25, 66, 10, 5]
vec = numvec(v)
OUTPUT:
vec =
'small'
Your input is greatly appreciated.
Thanks!!

 채택된 답변

You are overwriting all of x on each iteration. You need to write to x(i) instead of to x
Also, for i =length(v) only uses length(v) exactly, and not 1, 2, 3, and so on. You need 1:length(v)
Thirdly, for this particular purpose, you need to use " instead of ' -- so "small" instead of 'small' . 'small' is a character vector, a 1 x 5 array of char, rather than being a string() object, but "small" is a 1 x 1 string object.

댓글 수: 2

You may also want to preallocate x to be a string array of the same size as v before you start looping over the elements in v, so that you're replacing an existing element in x rather than growing x at each iteration.
x = repmat("high", size(v)); % Choosing one of the possible values arbitrarily
I implemented both solutions and it worked perfectly.
Thanks for the clarification, Walter and Steven!!!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by