How to save all outputs that are produced from each iteration in separated cell in one row of array and each row expresses an iteration then store it in one .mat file?

How to save all the output from each iteration in one .mat file?
Suppose we have the following program and I want to save Pd , C , M that are produced from each iteration in separated cell in one row of array and each row expresses an iteration then store it in one .mat file named Cases.mat.
Pd=[] ;
[Pd{1:7}]=ndgrid([0.5,1]);
Pd=reshape( cat(8,Pd{:}) ,[],7);
Pd = Pd'
for j = 1:size(Pd,2)
Pd(:,j)
C = 5*Pd(:,j)
M = 3*Pd(:,j)
end
Can Anyone help me to achive this?

 Accepted Answer

Pd = {};
[Pd{1:7}] = ndgrid([0.5,1]);
Pd = reshape(cat(8,Pd{:}),[],7).';
C = 5*Pd;
% M = your code is unclear
save('cases.mat','Pd','C')

5 Comments

@Stephen I want to save Pd , C and M that are produced from each iteration in one column array then save it in .mat file
Pd(:,j)
C = 5*Pd(:,j)
M = 3*Pd(:,j)
All of the data can be trivially calculated and saved as matrices, just like MATLAB is designed for.
Why make your data and code more complex than it needs to be?
Describe how you are going to use that data: what will load it from the MTA-file and how will it be processed?
@Stephen Actually, I want to perfom another type of Calculations on each column of Pd in each iteration and store it on C and M. I just want to get the the idea from this example how to store Pd , C and M that are produced from each iteration in separated cell in one row of array and each row expresses an iteration.
The most efficient approach is NOT to store them as separate variables, but to store the data in matrices/arrays.
If you are generating the data in a loop then you can use indexing to assign the data to those matrices, just like you would use indexing to get data out of a matrix. For example:
Pd = {};
[Pd{1:7}] = ndgrid([0.5,1]);
Pd = reshape(cat(8,Pd{:}),[],7).';
S = size(Pd);
C = nan(S); % preallocate!
M = nan(S); % preallocate!
for k = 1:S(2)
C(:,k) = 5*Pd(:,k); % presumably your calculation is more complex
M(:,k) = 3*Pd(:,k); % presumably your calculation is more complex
end
save('cases.mat','Pd','C','M')
Of course in this example the loop is not required, as my answer already showed.
If you still really really want to store the data as vectors then store them in two cell arrays.
Thank you so much @Stephen , your second code is working properly on my original code.

Sign in to comment.

More Answers (0)

Categories

Asked:

M
M
on 4 Mar 2022

Commented:

M
M
on 4 Mar 2022

Community Treasure Hunt

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

Start Hunting!