For loop overwriting previous answers rather than storing?

6 views (last 30 days)
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 :)
  2 Comments
Shane L
Shane L on 7 Dec 2018
I don't have access to the symbolic math toolbox, so I was not able to run your code, but I believe your problem is that you call syms x in every iteration of your for loop. Therefore, only the final value is stored in your output x. I would suggest using a different variable name for your symbolic variable and your output variable.
Gregory Woodhall
Gregory Woodhall on 7 Dec 2018
This also worked perfectly, thankyou :)
Didnt consider that at all

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 7 Dec 2018
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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!