How to create a matrix for plotting from a roots matrix in a loop?

1 回表示 (過去 30 日間)
Alejandro
Alejandro 2014 年 4 月 8 日
コメント済み: Alejandro 2014 年 4 月 8 日
Hello,
So my problem is that currently I have a script that solves a polynomial of 4th order and gives me all the roots for it. However since it is for an engineering application I only need the logical value given by one of the roots.
My code goes something like this
while (condition)
code;
r = roots(x);
end
and this runs as long as the condition is true.
Because the user ends up producing many values of r, I was wondering how I can take for example the 4th position of r or r(4) and make a matrix of all the values of r(4) produced by the loop so that I can plot them.
If it helps the problem asks the user to input a ratio of Oxygen to MEthane and r(4) is the temperature of the reaction.
I need to plot this temperature vs the ratio.
Also I looked at things like
for i = 1:10
y(i) = 1 + rand
end
but can't seem to get that working with what I want.
Thank You in advance and feel free to ask for clarifications if any.

採用された回答

Yoav Livneh
Yoav Livneh 2014 年 4 月 8 日
You can store the data into a vector:
results = [];
while (condition)
code;
r = roots(x);
results(end+1) = r(4);
end
This solution isn't ideal, since the variable results keeps changing size. If you know approximately how many iteration your while loop is going to have you can preallocate the variable. For example, if you never have more than 100 runs:
results = zeros(100,1); % pre allocate
n=0;
while (condition)
code;
r = roots(x);
n = n+1;
results(n) = r(4);
end
if n == 0 % no iterations
results = [];
else % keep only real results
results = results(1:n);
end
After the while loop we only keep the true results.
Hope this helps.
  1 件のコメント
Alejandro
Alejandro 2014 年 4 月 8 日
Thank You very much, this solved my problem.

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

その他の回答 (1 件)

Alejandro
Alejandro 2014 年 4 月 8 日
Thanks, I will try this tomorrow to see how it goes. I only really need 7 iterations for this specific problem. But I was aiming for any amount that the user wanted.
Again many thanks, will report back tomorrow.

カテゴリ

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