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]

답변 (1개)

Jan
Jan 2021년 2월 28일
편집: Jan 2021년 3월 2일

0 개 추천

"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?

카테고리

도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2021년 2월 28일

편집:

Jan
2021년 3월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by