Reputation: 791
I would like to write a function that accepts an array of any number of values and returns their changed values in a new array.
function zArray = y(xArray)
zArray = [];
for x = 1:size(xArray,2)
if x >= -2 && x < -1
z = ln(x + 2);
elseif x >= -1 && x < 0
z = (x + 1).^2;
elseif x >= 0 && x <= 2
z = (x + 1)/(x.^2 + 1);
else
z = -10
end
zArray(end + 1) = z;
end
end
I then call the function with:
[z1, z2, z3] = y([0, 1, -1])
Which gives me the following output and message:
z1 =
1.00000 0.60000 -10.00000
error: element number 2 undefined in return list
I am new to Matlab and am not sure how Matlab for loops and arrays work. If I understand correctly, I am not adding the changed values correctly to the array which is supposed to hold output values and therefore can not read them in this manner, but if I am not mistaken, array(end + 1) = z
is appending the element z
to the end of the array.
Am I making more than one mistake? Please point out any of them because I have troubles understanding the Matlab syntax, even though I do know how to program in some other languages.
Upvotes: 0
Views: 52
Reputation: 521
I think you desire the following thing but you are confused with syntax:
function zArray = y(xArray)
zArray = zeros(size(xArray));
for x = 1:size(xArray,2)
xVal = xArray(x);
if xVal >= -2 && xVal < -1
zArray(x) = log(xVal + 2);
elseif xVal >= -1 && xVal < 0
zArray(x) = (xVal + 1).^2;
elseif xVal >= 0 && xVal <= 2
zArray(x) = (xVal + 1)/(xVal.^2 + 1);
else
zArray(x) = -10;
end
end
end
Upvotes: 1