using a function with matrices

1 visualización (últimos 30 días)
David Dungan
David Dungan el 28 de Feb. de 2021
Editada: Jan el 2 de Mzo. de 2021
Hi! I am attempting to write a function that wil have three inputs that are all equally sized vectors, and use if statements to produce one vector as an output. I have my if stetments as a function file and my vectors prepared, but running the function with the vectors as inputs gives the error message that the output was not assigned during the call to my function. the function would look something like:
[rating] = rating(x,y)
if x <4
rating=1;
elseif x<10 && y<3
rating=2;
else
rating=3;
where x and y are vectors, and rating will be a vector of the same size as x and y where the values are determined using the x adnd y vectors. like rating([1 2],[6 2]) would give [1 2]

Respuestas (1)

Jan
Jan el 28 de Feb. de 2021
Editada: Jan el 2 de Mzo. de 2021
"function [rating] = rating(x,y)" does not match the information, that the function has 3 inputs.
"gives the error message that the output was not assigned during the call to my function" - please do not explain, what you see in the message, but post a copy of the complete message. This helps to solve the problems more efficiently.
The if command needs a scalar condition. If your x is a vector, Matlab inserts an all(x(:) < 4) automatically.
The output rating is a scalar also, not a vector. You either need a loop over the elements of the inputs:
function r = rating(x,y)
r = repmat(3, size(x)); % Pre-allocate the output
for k = 1:numel(x)
if x(k) < 4
r(k) = 1;
elseif x(k) < 10 && y(k) < 3
r(k) = 2;
% else Solved by the pre-allocation already:
% r = 3;
end
end
end
A matlab'ish alternative is a vectorized approach:
function r = rating(x,y)
r = repmat(3, size(x)); % Pre-allocate the output
r(x < 10 & y < 3) = 2;
r(x < 4) = 1;
end
You see the elegance?

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by