How to Store Output from Function Within Nested for Loop

I have the following code:
Fes=10:1:11;
Fe0=12:1:13;
for y=1:numel(Fes);
for z=1:numel(Fe0);
puppies(Fes(y),Fe0(z))
end
end
Puppies is a function that produces two vectors for each combination of Fes and Fe0. I would like to store the result of puppies in a table, contained within my workspace, that shows each result, labelled with the particular Fes and Fe0 combination that produced the result (with each result being the two vectors generated from an individual Fes and Fe0 combination).
How can I do this?

Réponses (1)

The same way you capture any output from a function. You might need an intermediate step to put your vectors in a cell first.
Fes=10:1:11;
Fe0=12:1:13;
for y=1:numel(Fes);
for z=1:numel(Fe0);
[A,B]=puppies(Fes(y),Fe0(z));
%now you can store A, B, Fes(y), and Fe0(z) in a table
end
end
Alternatively, you could store Fes and fe0 in a table and then use rowfun.

4 commentaires

Hi Rik,
Thanks for responding. When I try and do it this way, my workspace only records the values for A and B that it ran last. For instance, because my code runs puppies with Fes=11 and Fe0=13 last, it only records the values of A and B that are generated when Fes=11 and Fe0=13, instead of showing all the other values with it.
How would I go about recording all the values of A and B with all of the Fes and Fe0 values?
You wanted to store the results in a table. That is why I wrote that comment: my intention was that you would write the code to store those values in a table the way you prefer. Because every element in a table can only contain 1 value, you will need to put them in a cell first.
I would use a 3D array instead of a table, but that depends on what you are planning to do next.
Jonathan Pinko
Jonathan Pinko le 10 Mai 2020
Modifié(e) : Jonathan Pinko le 10 Mai 2020
Hi Rik,
Thanks again. I like your idea of putting my results into a 3D array rather than a table, and I think that putting my data into two 3D arrays would be best. In this scenario, one 3D array would be (Fes,Fe0,A), and the other would be (Fes,Fe0,B), with A and B being the two different outputs from my code.
I apologize for being so new at this, and bothering you these basic questions, but how would I go about creating these 3D arrays?
Fes=10:1:11;
Fe0=12:1:13;
for y=1:numel(Fes)
for z=1:numel(Fe0)
if y==1 && z==1
[a,b]=puppies(Fes(y),Fe0(z));
A=zeros(numel(Fes),numel(Fe0),numel(a));
A(1,1,:)=a;
B=zeros(numel(Fes),numel(Fe0),numel(b));
B(1,1,:)=b;
else
[A(y,z,:),B(y,z,:)]=puppies(Fes(y),Fe0(z));
end
end
end
function [a,b]=puppies(y,z)
a=rand(100,1);
b=rand(5,1);
end

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Version

R2019b

Commenté :

Rik
le 11 Mai 2020

Community Treasure Hunt

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

Start Hunting!

Translated by