필터 지우기
필터 지우기

For loop overwriting previous answers rather than storing?

조회 수: 4 (최근 30일)
Gregory Woodhall
Gregory Woodhall 2018년 12월 7일
댓글: Gregory Woodhall 2018년 12월 7일
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
Shane L
Shane L 2018년 12월 7일
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 2018년 12월 7일
This also worked perfectly, thankyou :)
Didnt consider that at all

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2018년 12월 7일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by