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

3 views (last 30 days)
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.

Accepted Answer

Yoav Livneh
Yoav Livneh on 8 Apr 2014
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.

More Answers (1)

Alejandro
Alejandro on 8 Apr 2014
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.

Categories

Find more on Polynomials 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!