3 views (last 30 days)

So I have written a loop that runs a function for a given m to give a specific time_hours value (for that given m). The program works and I get all the values I need, but how would I save these values in an array to plot against m later on? I'm not sure how this would work as I have used fzero to calculate the time_hours values on each iteration and fzero values cannot be indexed? Thanks for any help, here is my code:

alpha = 0.7e-7; rho = 0.1 .^(1/3); %m = [4:0.1:8];

for m = 4:0.1:8

[term, scarysum, summation_t, f, time_seconds, time_hours] = tcalc(alpha, rho, m);

end

function [term, scarysum, summation_t, f, time_seconds, time_hours] = tcalc(alpha, rho, m)

scarysum = 0;

for k = 1:30

syms t

term = ((-1).^(k-1))./k .* sin(k.*pi.*rho) .* exp((-1 .* k.^2 .* pi.^2 .*alpha.*(1360.*pi).^(2/3).*t)./m.^(2/3));

scarysum = scarysum + term;

end

summation_t = matlabFunction(scarysum);

f = @(t) (2./(pi*rho) .* (summation_t(t))) - 0.7125;

time_seconds = fzero(f,14400);

time_hours = time_seconds ./ 3600;

disp(time_hours)

end

Allen
on 18 Dec 2019

Edited: Allen
on 18 Dec 2019

If your function is returning scalar values that are being overwritten during each iteration of your for-loop, try the following as a replacement to your for-loop.

[term, scarysum, summation_t, f, time_seconds, time_hours] = arrayfun(@(m) tcalc(alpha, rho, m), 4:0.1:8);

% This is essentially the same as rewriting the for-loop to something like this, which changes the size

% of the output variables each iteration and appends the new value to the end of each variable.

rng = 4:0.1:8;

for m = length(rng)

[term(m), scarysum(m), summation_t(m), f(m), time_seconds(m), time_hours(m)] = tcalc(alpha, rho, rng(m));

end

Cameron B
on 18 Dec 2019

options = optimset('PlotFcns',@optimplotfval);

scarysum = 0;

for k = 1:30

syms t

term = ((-1).^(k-1))./k .* sin(k.*pi.*rho) .* exp((-1 .* k.^2 .* pi.^2 .*alpha.*(1360.*pi).^(2/3).*t)./m.^(2/3));

scarysum = scarysum + term;

end

summation_t = matlabFunction(scarysum);

f = @(t) (2./(pi*rho) .* (summation_t(t))) - 0.7125;

[time_seconds,fval,exitflag,output] = fzero(f,14400,options);

time_hours = time_seconds ./ 3600;

disp(time_hours)

fig = gcf;

dataObjs = findobj(fig,'-property','YData');

y1 = dataObjs(1).YData;

x1 = dataObjs(1).XData;

You'll have to save y1 and x1 each time, but that's how you'd extract the data.

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

Start Hunting!
## 0 Comments

Sign in to comment.