Save .Mat in Every Iterations - matlab

Im Working on Simulation Dehumidification Process, i should save .Mat file in every loop, my program flowchart is:
enter code here
for m=9:2:21
for kk=1:ll
for jj=1:mm
for ii=1:nn
...
...
...
end
end
end
A=min(X-Y)
end
for example
mm=9 then A=1
mm=11 then A=2
..., How i can Plot A with mm?
and How i can Save .Mat file in every mm iteration? Thanks.
Blockquote
%A=(7*1)Matrix %9:2:21=7(Number)

If you want to save a .mat-file for each iteration the only thing you need to do is to generate a unique filename for each iteration within the loop. This can be done using format strings, for instance in your case something like
filename = sprintf('output_kk=%d_jj=%d_ii=%d.mat', [kk jj ii]);
save(filename);
You have the option to save specific variables by adding them as options to the save command. For more about string formatting I'd suggest you check out the sprintf documentation.
I'm not sure whether this is the most efficient way to do it. Depending on the number and size of output variables you're interested in you can also create a cell structure and save your data into a new cell for each iteration.

Related

save variables: add new values to a new row in each iteration MATLAB

I have a loop as below
for chnum=1:300
PI=....
area=....
save ('Result.mat' ,'chnum' ,'PI' ,'area',' -append') %-append
%% I like to have sth like below
% 1, 1.2,3.7
% 2, 1,8, 7.8
% .....
end
but it doesn't save. Do you have any idea why?
Best
Analysis of the Problem
The matlab help page for save states that the -append option will append new variables to the saved file. It will not append new rows to the already saved matrices.
Solution
To achieve what you intended you have to store your data in matrices and save the whole matrice with a single call to save().
PI = zeros(300,1);
area = zeros(300,1);
for chnum=1:300
PI(chnum)=.... ;
area(chnum)=.... ;
end
save ('Result.mat' ,'chnum' ,'PI' ,'area');
For nicer memory management I have added a pre-allocation of the arrays.
Well, even if it's not part of the question, I don't think that you are using a good approach to save your calculations. Reading/writing operations performed on the disk (saving data on a file is falls in this case) are very expensive in terms of time. This is why I suggest you to proceed as follows:
res = NaN(300,2)
for chnum = 1:300
PI = ...
area = ...
res(chnum,:) = [PI area]; % saving chnum looks a bit like an overkill since you can retrieve it just using size(res,1) when you need it...
end
save('Result.mat','res');
Basically, instead of processing a row and saving it into the file, then processing another row and saving it into the file, etc... you just save your whole data into a matrix and you just save your final result to file.

Scan files in a Directory - MATLAB

I am trying to load files from my directory with matlab. The code is fairly simple :
for j =1:8
people_names=dir('~/Desktop/Directory/Data/*.mat');
people_name=people_names(j).name
resp=load('~/Desktop/Directory/Data/people_name');
However, the load command fail because it reads "people_name" as a string and not its value.
D'oh. Your first statement in your for loop should be outside of it. You want to find all files first, then loop over each file. You're doing that inside your loop statement, and that will probably not give you what you want.
You also are using load wrong. You'd want to use the actual string of people_name itself. You also will want to loop over all possible file names, not just the first 8:
people_names=dir('~/Desktop/Directory/Data/*.mat'); %// Change
for jj = 1:numel(people_names) %// Change
people_name=people_names(jj).name;
resp=load(people_name); %// Change
%// Rest of your code here....
%//...
end

save Matlab data in a .xls file

I want to save data in a results.xls file which I want to set its first row "header" with a specific names lets say a,b,c,d,e. So, basically I have matlab function func1 which loops n times. In this loop, I call another function func2, where I do some processes and save save variables lets say a_res,b_res, c_res,d_res,e_res, I want to save those variables in each iteration in the results.xls file, where if the loop has 10 iterations then this means the results file will have 10 rows and 5 columns + the header row, so 11 in total. Could anyone please advise how this can be done in Matlab?
the below image shows the desired output where the first row is headings, then each row after that will be filled with variables calculated in each iteration of the loop.
EDIT:
Following the proposed solution, I used this:
save('results.xls', 'name','number_of_points','blood_level','width','sugval', '-ASCII');
where 'name','number_of_points','blood_level','width','sugval', are variables holding strings. But when I open the excel file this is what I get results.xls if anyone could please advise.
p = rand(1, 10);
q = ones(10);
save('test.xls', 'p', 'q', '-ASCII')
This works for me. It saves me on the first row the random values of "p" and beneath I have the values for "q". You might check it out. Hope it helps

csvwrite in loop with numbered filenames in matlab

kinda new to matlab here, searching the csvwrite tutorial and some of the existing webportals regarding my question couldn't find a way to pass my variables by value to the output file names while exporting in csv; providing my bellow scripts, i would like to have the output files something like output_$aa_$dd.csv which aa and dd are respectively the first and second for counters of the scripts.
for aa=1:27
for dd=1:5
M_Normal=bench(aa,dd).Y;
for j=1:300
randRand=M_Normal(randperm(12000,12000));
for jj = 1:numel(randMin(:,1)); % loops over the rand numbers
vv= randMin(jj,1); % gets the value
randMin(jj,j+1)=min(randRand(1:vv)); % get and store the min of the selction in the matix
end
end
csvwrite('/home/amir/amir_matlab/sprintf(''%d%d',aa, bb).csv',randMin);
end
end
String concatenation in MATLAB is done like a matrix concatenation. For example
a='app';
b='le';
c=[a,b] % returns 'apple'
Hence, in your problem, the full path can be formed this way.
['/home/amir/amir_matlab/',sprintf('%d_%d',aa,bb),'.csv']
Furthermore, it is usually best not to specify the file separator explicitly, so that your code can be implemented in other operating systems. I suggest you write the full path as
fullfile('home','amir','amir_matlab',sprintf('%d_%d.csv',aa,bb))
Cheers.

How to store fig in .mat file?

Is it possible to store the matlab figure inside a mat file, where the variable are stored.
I got into a scenario where i generated some plot from the variable stored in the mat file. Currently im storing the figure as a separate file, this means, i have a 1 file for variables and another file for figure. But i would like to bundle them together in a single file.
How about selecting both files in the windows explorer and zip them? ;-)
Seriously, while I do not know of a way to do exactly what you want (what is it, exactly, anyway? Do you expect the figure to pop up once you've typed load variables.mat and pressed enter?) I see this way around it:
You could store the command(s) needed to generate the figure in an anonymous function or as a string and save it along with all other variables. Then, after loading the .mat file, you call that function or eval on the string and the figure will be regenerated.
x=sort(rand(1,100)); y=sort(randn(1,100)); %# sample data
makefig = #() plot(x,y,'g.'); %# anonymous figure-generating function
save myDataAndFigure
clear all
load myDataAndFigure
makefig()
...or, with a string (e.g. when including formatting and axis-labelling commands)
x=sort(rand(1,100)); y=sort(randn(1,100)); %# sample data
figcmd = 'plot(x,y,''g.''); xlabel(''sort(U(0,1)''); ylabel(''sort(N(1,0)'');'
save myDataAndFigure
clear all
load myDataAndFigure
eval(figcmd)
The latter should save memory when the involved data are large, since the anonymous function object contains all the data it needs, i.e. its own "copy" of x and y in the example.
There's an article here on fig file format and how it's actually a mat file in a disguise.
So you can take the fig and store its data in a structs and save them as a mat file, then load the mat file and make fig out of the structs you saved.
How about storing data and functions in instances of a class and unsing the functions later to plot the data?
Actually this is surprisingly easy to do.
Suppose you have just created the figure in question. Converting the figure handle into a struct yields the corresponding hierarchical elements (including the data, labels, everything) required to display the figure.
If desired, this struct may then be saved to a mat file just as though it was data. (It is, in fact.) To view the contents of the struct as a figure again simply reconvert it to a handle with struct2handle.
% The line below converts the current figure handle into a struct.
this_fig = handle2struct(gcf)
% The line below converts the struct "this_fig" back to a figure handle and displays it.
h = struct2handle(this_fig,0);