MATLAB: For loop overwriting previous answers rather than storing

for loopfunctionhelp meif loopMATLAB and Simulink Student Suitepleasestoring answers

Im trying to run a basic loop inside of a function, so that if the user inputs a range of data for one of the values, they will be returned with a range of answers that can then later on be used for other means. (for example plotting a graph)
So far I have,
%% Question 1
function Question1 = Question_1(k1,k2,d,W)
clc, close;
for i=1:numel(W)
if W < k1*d
x(i) = W/k1;
else
syms x
eqn2 = (k1*x)+(2*k2*(x-d)) == W;
x(i) = solve(eqn2(i),x);
end
end
disp('Distance x equals:')
disp(x)
end
which works perfectly fine when inserting the variables with only one input,
for example inputing
>> Question_1(10^4,1.5*10^4,0.1,1500)
will return me the answer
'Distance x equals:'
9/80
But as soon as i change the input to
>> Question_1(10^4,1.5*10^4,0.1,0:100:3000)
Im returned with the answer
Distance x equals:
[ x, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3/20]
After browsing these forums for ages, and watching a few videos explaining how to store data in this way, im lost on where the mistake is. Any help would be appreciated even if its given in hints 🙂

Best Answer

if W < k1*d
How does if behave if the condition is not a scalar (in your second case it is a vector.) Let's check the documentation.
if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false.
In your second case, W is not empty and neither is k1*d so the expression (W < k1*d) is nonempty. But does it contain only nonzero elements? Or is at least one element of W not less than k1*d?
You could try removing the for loop and using logical indexing or you could have the body of your for loop operate on each element of W in turn rather than the whole array each iteration.