Function - Input is a numeric vector x (any length). Return value is a list of string and matlab
1 view (last 30 days)
Show older comments
Emmanuel Matata Bili Bili
on 4 Mar 2020
Commented: Emmanuel Matata Bili Bili
on 5 Mar 2020
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!!
0 Comments
Accepted Answer
Walter Roberson
on 4 Mar 2020
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 Comments
Steven Lord
on 4 Mar 2020
Edited: Steven Lord
on 4 Mar 2020
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
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!