pyCthon
pyCthon

Reputation: 12341

running a function and saving multiple outputs in matlab with different inputs

lets say you have some function

x = foo(alpha, beta);

and you want to test the function for different alpha values while saving the different x values with a name associated to the different alpha values.

For example if alpha = 1:1:10; then then i would like to save x_1 , x_2 ,........,x_9 , x_10 as separate results

I've tried running different loops and such but I can't figure out how to keep the x values from being replaced

Upvotes: 2

Views: 3878

Answers (1)

Jonas
Jonas

Reputation: 74930

There are several ways to do this

For example, if you want to save results to disk, you can run

alpha = 1:10;

for ii=1:length(alpha)

  x = foo(alpha(ii),beta);

  %# save to disk
  save(sprintf('run_%i.mat',ii),'x');

end

If, instead, you want to store all outputs, so that you can plot, for example, you can store them in an array

alpha = 1:10;
x = zeros(size(alpha));

for ii=1:length(alpha)

  x(ii) = foo(alpha(ii),beta);

end

%# now you can plot the results
plot(alpha,x)

Note that the above assumes that the output of foo is scalar. If the output is always a m-by-n array, you initialize x as zeros(m,n,length(alpha)), and assign x(:,:,ii) each loop. If the output is arrays of different size, you initialize x as a cell array, as x = cell(size(alpha)), and assign the output of foo to x{ii}.

Upvotes: 2

Related Questions