Asked by ADNAN KIRAL
on 21 Nov 2018

how can save all variables which are in function ? i would like to extract those variables out of function. if i just use "save" command in function, it will delete just previous variable. however, i need all of them not the last one. can anyone help

Answer by Majid Farzaneh
on 21 Nov 2018

Accepted Answer

Hi.

You can make a string in each run for your function and then use the string for your file name. for example you may use a global counter in function like this:

function ....

global counter

counter=counter+1; %

str=['file' , num2str(counter) , '.mat'];

...

...

...

save(str)

end

ADNAN KIRAL
on 21 Nov 2018

can anyone please answer my question ?

Majid Farzaneh
on 21 Nov 2018

First, modify your function:

function [f,w]= F_xy(x,y)

if x>4

w=30;

else

w=20;

end

f=3.*exp(-x)-0.4*y+w; % change the function as you desire

end

Now you have 2 outputs.

Then tou can change main file like this:

clc;

clear all;

h=0.5; % step size

x = 0:h:3; % Calculates upto y(3)

y = [zeros(1,length(x))];

for i=1:(length(x)-1) % calculation loop

[k_1(i), w_1(i)] = F_xy(x(i),y(i));

[k_2(i), w_2(i)] = F_xy(x(i)+0.5*h,y(i)+0.5*h*k_1);

[k_3(i), w_3(i)] = F_xy((x(i)+0.5*h),(y(i)+0.5*h*k_2));

[k_4(i), w_4(i)] = F_xy((x(i)+h),(y(i)+k_3*h));

y(i+1) = y(i) + (1/6)*(k_1(i)+2*k_2(i)+2*k_3(i)+k_4(i))*h; % main equation

end

You can also plot k or w like this:

figure, plot(k_1)

figure, plot(k_2)

figure, plot(k_3)

figure, plot(k_4)

figure, plot(w_1)

figure, plot(w_2)

figure, plot(w_3)

figure, plot(w_4)

ADNAN KIRAL
on 21 Nov 2018

cheers @Majid Farzaneh

i got that

Sign in to comment.

Answer by Cris LaPierre
on 21 Nov 2018

The specifics are a little unclear, but here are some options.

Consider saving them to a mat file with a unique filename. However, they will still contain the same variable names, so when loaded back into the workspace, will replace any existing variables with the same names.

You could return them through the function output. That allows you to assign them to variables with whatever name you want, allowing you to have both at the same time.

If there are a lot of variables, consider using a structure so you only have to pass out one variable.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Stephen Cobeldick (view profile)

## Direct link to this comment

https://fr.mathworks.com/matlabcentral/answers/431202-how-can-save-all-variables-which-are-in-function-without-deleting-previous-one#comment_640583

## ADNAN KIRAL (view profile)

## Direct link to this comment

https://fr.mathworks.com/matlabcentral/answers/431202-how-can-save-all-variables-which-are-in-function-without-deleting-previous-one#comment_640697

Sign in to comment.