MATLAB Answers

0

How to save every iteration and answer for a numerical Solve function in a for loop

Asked by lindsey Cameron on 26 Nov 2014
Latest activity Commented on by mashtine on 27 Nov 2014
Hi everyone,
I have the following code
syms x g
for g=1.3099*10^15:0.05*10^15:2.6*10^15
f=(((1.1096*10^17-(5.201*10^16)*(6.667*(x - 255)/x)^(1/3))/(g)) + 255-x);
soln=solve(f,x)
end
I would like to save every value of g with its corresponding solution of x so that I can plot them,
Anyone got any ideas or changes I can make to achieve this?
Cheers,
Lindsey

  0 Comments

Sign in to comment.

1 Answer

Answer by mashtine on 26 Nov 2014
Edited by mashtine on 26 Nov 2014

Hi Lindsey,
You can preallocate g outside of your loop and then within your loop you can assign each row and col the corresponding g value and solution:
syms x g
g=1.3099*10^15:0.05*10^15:2.6*10^15;
for i = 1:length(g) % Assigns i for each value within in g
f=(((1.1096*10^17-(5.201*10^16)*(6.667*(x - 255)/x)^(1/3))/(g(1,i))) + 255-x); % Will work on each g value and provide and f value
soln=solve(f,x);
finalsoln(1,i) = g;
finalsoln(2,i) = soln;
end
This code will of course be different if you want your finalsoln matrix to be a 1xi or a ix1 matrix. However I am not too sure about using sym and the resultant x and the code as it stands raise a dimension mismatch but may be on my end.
Hope it makes sense

  3 Comments

Hi Masao,
THank you for your answer,
I get the following error,
Subscripted assignment dimension mismatch.
Would it be easier to just right the values to a text file? if so, how do I do that?
Cheers,
Lindsey
I guess my goal at the end is to plot the change in x due to a change in g, do I even need to store it for that?
Hi Lindsey,
As I am not familiar with the syms function (symbiotic relationship?) I am not sure how x is influenced. Your subscript dimension mismatch lies with this.
For instance, when this is run by itself:
syms x g
g=1.3099*10^15:0.05*10^15:2.6*10^15;
f=(((1.1096*10^17-(5.201*10^16)*(6.667*(x - 255)/x)^(1/3))/(g(1,i))) + 255-x);
g,x and f are produced but are empty sym variables and this is what caused the dimension mismatch. Did you define x before?

Sign in to comment.