フィルターのクリア

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.
  1 件のコメント
Gregory Woodhall
Gregory Woodhall 2018 年 12 月 7 日
logical indexing seems like a great way to go, thankyou :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by