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!!

 Akzeptierte Antwort

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 Kommentare

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!!!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by