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
Related
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.
I want to do some operations on images and write some data into a txt file.Here is what I am doing for one image-
clc;
image=imread('im.png');
.... %do some operations
....
....
fileID=fopen('first.txt','w');
.... %write onto the txt file
....
fclose(fileID);
But I want to do this for many images.I have stored all the images in a folder.Also, I want to continue writing in the same text file immediately after where I left off for the previous image.How can I modify my code to achieve this?
Well that's pretty simple. Use a loop and loop over all of your images, do your processing on it, then append to the text file. What'll be easier is that you just open the file for your text ONCE, write for as many times as you have images, then finally close it.
Something like this:
folder = ...; %// Place folder here - Example: folder = fullfile('D:', 'images');
fileID=fopen('first.txt','w'); %// Open up the file for writing
f = dir(fullfile(folder, '*.png')); %// look for all PNG files in this folder
for idx = 1 : numel(f)
filename = fullfile(folder, f(idx).name); %// Get the file name
im = imread(filename); %// Read the image in
.... %do some operations
....
....
.... %write onto the txt file
....
fprintf(fileID, '\n\n'); %// Put two carriage returns to make way for next file
end
fclose(fileID);
The function dir scans for all files that match a particular expression. In your case, you want to find all PNG files in a particular folder of your choosing. I assume that this is stored in the variable folder. We then open up the file first before we do anything to the images, then loop over each of the found images with dir. Take note that when you use dir, it only finds the relative paths to the files (i.e. just the names themselves). If you want to locate where the actual images are, you need the absolute paths, which is why we use fullfile.
So, for each PNG image that's in the folder, load it in, do your processing on it, write to your file and I make sure that I put in two carriage returns to separate each result. You repeat this for each PNG image until you exhaust all of them from the folder. Once you're done, you close the text file.
Minor note
image is an actual function in MATLAB that visualizes a matrix of values as an image with a specified colour map. You should probably rename this variable to something else so you don't overshadow the function in case other scripts / functions you write use this function.
This is the matlab equivalent to this question. Essentially, I'm wondering if there is a way to avoid explicitly writing the exists check for a variable before assigning it.
You may use
persistent varname
if isempty(varname)
varname=heavyComputation()
end
This will only recompute varname at startup and after each clear fun and clear all.
Why avoid exist? This is exactly what it is for:
if ~exist('t', 'var')
t = 1
end
For your specific use case, if you don't want a certain variable to be recalculated, save it into a MAT-file and check for its existence before recalculating. For example, if you are calculating A, then you can do something along the lines of:
if exist('mycalcs.mat', 'file')
load('mycalcs.mat', 'A') %// Load precalculated A
else
A = do_some_calculations(); %// Calculate A
save('mycalcs.mat', 'A'); %// Save it to a workspace file
end
This allows you to rerun the script without repeating calculations, even after clearing the variable in question or closing MATLAB altogether.
You could use the syntax who(variable_name) to check if the variable exists in the workspace as shown here: http://www.mathworks.com/help/matlab/ref/who.html
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.
I have 2 matlab programs : prog1.m and prog2.m
I have to use a 2-D matrix M in both programs.
I have loaded the matrix in prog1.m (manually from a TEXT FILE).
I have to run both the programs ~100 times (for different matrix each time) . So now i have ran prog1.m 100 times , every time with different matrix .
Now is turn of prog2.m but i don't want to load matrix manually again.
I have the saved (100 copies of) prog1.m which contains M to be used in prog2.m also . Is there a method to load M from prog2.m to prog1.m ?
I want to add some code in prog2.m which automatically loads M from prog1.m .
PS: I am very new to MATLAB
If prog1 and prog2 are not already functions, rewrite them as functions. For example, the first line in them may look like:
function [out1 out2] = prog1(M)
function out = prog2(M)
Then, write a third function which, given a filename, loads the data, calls prog1 and prog2 and optionally saves the data in an appropriate form (you can use fileparts and fullfile to automatically create a new filename based on the input - e.g. given data101.txt, return data101_proc.mat. Bare bones of such a function would be along these lines:
function M = prog3(fname)
M = load(fname); % or whatever method is required for loading this data
%call prog1 and prog2
[out1 out2] = prog1(M);
out3 = prog2(M);
%make new filename
[fpath,fname2,ext] = fileparts(fname);
fname_out = fullfile(fpath, [fname2,'_out','.mat']);
%save data - depends on what outputs are and what you need to do with them later
save(fname_out, 'out1','out2','out3','M');
end
Finally, as babaea mentioned, you can use ls or dir, make up a list of the files you want to use, and create a loop which calls the above function on each file in turn.
The most efficient way of doing what you want to do is to read directly from the text file using textscan:
http://www.mathworks.co.uk/help/matlab/ref/textscan.html
If the formatting in the text files are the same, you can read from one file at a time, do your process then change the name and run again.
You can make the process more automated by changing the name of the file from which data is read dynamically in a loop around your main program. But the way to do this depends on the name of the text files.