Save loop results - matlab

I have a simple question but I don't know how to solve it.
I want to process all the files in a folder and I want to write the output values on a separate line on a matrix. After direct the folder and get the list of the files and their names
filePattern=fullfile( myPath,'*.txt')
I applied a 'loop'. To save the results on each line for every file, this is what I'm doing but it doesn't work (the code works with one file, not with all of them).
text= {baseFileName, result2b, result3b, result4b, result5b};
Is there something wrong?
Thanks in advance! Greetings,
Emma
PD)
myPath = 'C:\SP\';
% if ~isdir(myPath)
% errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
% uiwait(warndlg(errorMessage));
% return;
a= dir (fullfile(myPath,'*.DIM')); %
fileNames = { a.name };
filePattern=fullfile( myPath,'*.txt');
txtFiles= dir(filePattern);
for k = 1:length(txtFiles)
baseFileName=txtFiles(k).name;
fullFileName= fullfile(myPath,baseFileName);
fid=fopen(fullFileName, 'r+');
for i = 1:18
m{i} = fgetl(fid);
end
result2 = m{18};
result2b= result2([12:19]);
(...)
EDIT:
I added a screenshoot about my variables. Is it possible because of the txtFiles is wrong?

Related

Filename with variables ( filename_L=10.mat)

I would like to save a workspace with the result as 14-Nov-2019_094655_script name_L10_P50.mat.
Data and time I will add as datestr(now, 'dd-mmm-yyyy_HHMMSS', but I don't know how to add a scrip name and variables in the filename.
script_name is the name of the script that I run, L10_P50 are values L and P, which are changed in every run of the script. (L10_P50 means L=10 and P=50 in this run).
how to implement it?
edit 1:
I would like to increase the resolution. For that I have written :
fileNamefig = [dstr, '_',flname, '_Num', num2str(loops_num),'_N', num2str(Nfft), '.jpg'];
saveas(fig,['C:\Users\Matlab\results\fig_files\',fileNamefig])
set(fig,'PaperPositionMode','auto')
print(fig, '-djpeg','-r600','fileNamefig')
It dosnt work. HOw to rewrite it?
% your variables
L = 10;
P = 50;
% date string
dstr = datestr(now, 'dd-mmm-yyyy_HHMMSS');
% file name
flname = mfilename;
% cancatanate all strings together
matname = [dstr, '_',flname, '_L', num2str(L),'_P', num2str(P), '.mat'];
% save finally
save(matname)
'''

Matlab skipping subfolders

I have a folder containing sequential subfolders 000001_wd, 000002_wd,... in which I'm reading data contained in a file called 'plane.txt'. Some of the subfolders don't contain that file. I wish to skip them in a for-if else loop, but it is unable open file.
Tried changing or adding paths but nothing seems to work
workdir = 'D:\wass\test\output_925\';
cd(workdir)
data_frames = [1:1:37];
nframes = numel(data_frames);
V = zeros(nframes,3);
times = zeros(nframes,1);
ii=1;
prev = cd(workdir);
for frame = data_frames
fprintf('Processing frame %d\n',frame);
wdir = sprintf( '%s%06d_wd/', workdir, frame);
cd(wdir)
if exist('plane.txt')
plane_data = importdata([wdir,'plane.txt']);
times(ii) = double(ii-1)/fps;
else
times(ii) = double(ii-1)/fps;
end
ii=ii+1;
end
cd(prev);
fprintf('Saving data...\n');
I want to just continue through the loop until the last subfolder. Is there something I'm missing because the file I'm skipping is in a subfolder of my sequence?
The statement exist('plane.txt') tests to see if the file 'plane.txt' exists in the current directory. If it does, you read a file in the wdir subdirectory. Obviously, you haven't tested if that file exists.
I would simplify your code by reading the data within a try/catch block:
workdir = 'D:\wass\test\output_925\';
data_frames = 1:37; % <- don't use square brackets here, they're useless
nframes = numel(data_frames);
times = zeros(nframes,1);
for ii=1:nframes
frame = data_frames(ii);
fprintf('Processing frame %d\n',frame);
wdir = sprintf( '%s%06d_wd/', workdir, frame);
try
plane_data = importdata([wdir,'plane.txt']);
% do something with plane_data here...
catch
% ignore error
end
times(ii) = double(ii-1)/fps;
end
% ...
Note that I never used cd. You don't need to change directories to read data, and it's always better not to. The importdata statement uses an absolute path, so it does not matter what the current directory is.
A different approach involves getting a list of all files that match 'D:\wass\test\output_925\*\plane.txt':
files = dir(fullfile(workdir, '*', 'plane.txt'));
for ii=1:numel(files)
file = fullfile(files(ii).folder, files(ii).name);
plane_data = importdata(file);
% do something with plane_data here...
end

MATLAB - create a list for multiple files

I dont know if the title is appropriate, but i need to import several files e.g. 25 (files like info.asd , ina.asd, sdd.asd etc). So in my opinion its possible to import them via a for loop instead of hardcoding the operation. Any ideas how to implement the list in matlab, so the software 'd know what to import?
You can do it without loop with this function. sPath is the path containing your files and sExt is the extension of the files you want to list.
function cList = fileList(sPath, sExt)
if nargin == 1
sExt = '.asd';
end
% List files in the given path
stDir = dir(sPath);
tDir = struct2table(stDir);
tFile = tDir(~tDir.isdir, :);
% Keep only file with the right extension
cList = tFile.name;
[~, cList, cExt] = cellfun(#fileparts , ...
cList , ...
'UniformOutput', false);
vIsIni = cellfun(#(x) strcmpi(x, sExt), cExt);
cList = cList(vIsIni);
end

Reconstruct directories from file MATLAB

Thanks for your help.
The problem is:
I need the user to select a file based on an extension lets say .tif. I used the standard method, i.e.
[flnm,locn]=uigetfile({'*.tif','Image files'}, 'Select an image');
ext = '.tif';
But I need to fetch other image files from other subdirectories. Say the directory name returned to locn is: /user/blade/checklist/exp1/trial_1/run_1/exp001.tif. Image goes to exp100.tif.
I want to access:
/user/blade/checklist/exp1/trial_1/run_2/exp001.tif.
Also access:
/user/blade/checklist/exp1/trial_2/run_2/exp001.tif.
Up to trial_n
But if I list directory in /user/blade/checklist/exp1/, I get all folders therein from where I can reconstruct the right path. The naming structure is orderly.
My current solution is
[flnm,locn]=uigetfile({'*.tif','Image files'}, 'Select an image');
ext = '.tif';
parts = strsplit(locn, '/');
f = fullfile(((parts{end-5}),(parts{end-4}),(parts{end-3}),(parts{end-2}),(parts{end-1}));
Which is really ugly and I also lose the first /. Any help is appreciated.
Thanks!
First, get the file location as you did; note a small change I've made to make use of the variable ext.
ext = '.txt';
[flnm,locn]=uigetfile({['*',ext]}, 'Select an image');
parts = strsplit(locn,'/');
root = parts(1:end-4);
parts has 2 information - 1) path of the selected file; 2) path of your working folder, checklist, which you need. So root has the working folder.
Then, list out all the files you wanted, and put them in a cell array.
The file names should contain partial (subfolder) paths; it's not difficult to follow the pattern.
flist = {'trial_1/run_1/exp001.tif', ...
'trial_1/run_1/exp002.tif', ...
'trial_1/run_2/exp001.tif', ...
'trial_2/run_1/exp001.tif', ...
'trial_2/run_2/exp001.tif'};
I just enumerated a few; you can use a for loop to automatically generate trial_n and expxxx.tif. An example code to generate the complete file list (but not "full paths") -
flist = cell(10*2*100,1);
for ii = 1:10
for jj = 1:2
for kk = 1:100
flist{sub2ind([10,2,100],ii,jj,kk)} = ...
sprintf('trial_%d/run_%d/exp%03d%s', ii,...
jj, kk, ext);
end
end
end
Finally, use strjoin to concatenate the first part (your working folder) and second part (needed files in subfolders). Use cellfun to call strjoin for each cell in the file list cell array, so for every file you want you get a full path.
full_flist = cellfun(#(x) strjoin([root, x],'/'), ...
flist, 'UniformOutput', false);
Example output -
>> locn
locn =
/home/user/Downloads/exp1/trial_1/run_1/
>> for ii = 1:5
full_flist{ii}
end
ans =
/home/user/Downloads/trial_1/run_1/exp001.tif
ans =
/home/user/Downloads/trial_1/run_1/exp002.tif
ans =
/home/user/Downloads/trial_1/run_2/exp001.tif
ans =
/home/user/Downloads/trial_2/run_1/exp001.tif
ans =
/home/user/Downloads/trial_2/run_2/exp001.tif
>>
Note: You can either use
strjoin(str1, str2, '/')
or
sprintf('%s/%s', str1, str2)
They are equivalent.

Import datasheet iteration matlab - name to exist outside of function

So have some simple collumated data in text files named like:
Hm_slit_01.txt...Hm_slit_21.txt; Hs_slit_01.txt...Hs_slit_23.txt; Sm_slit_01.txt...Sm_slit_27.txt; Ss_slit_01.txt...Ss_slit_32.txt etc...
and I need to import it as datasheets into matlab, idealy with the same name but no .txt.
So I have created a function that takes a prefix Hm, Hs ... and a final number to iterate the file naming up to. BUT it doesn't save the datasheet externally in the workplace.
Here is the code.
function [datasheet] = imp_vrad(prefix,numslits)
%[data] = imp_vrad(prefix,numslits)
% imports data with filename <prefix>_slit_<##>.txt
% to be a matlab datasheet data = <prefix>_slit_<##>
% here ## starts from '01' and goes to 'numslits'
% FILES MUST BE IN WORKING DIRECTORY!
for currslit=1:numslits
if currslit < 10
filename = [prefix '_slit_0' num2str(currslit) '.txt']; %names file
data = [prefix '_slit_0' num2str(currslit)]; %names datasheet
else
filename = [prefix '_slit_' num2str(currslit) '.txt']; %names file
data = [prefix '_slit_' num2str(currslit)]; %names datasheet
end
disp(['importing ' filename ' as ' data])
importdata(filename); %imports the data
end
end
The line in question is the last line. I have also tried data=importdata(filename); to no avail.
Thanks in advance!
I'm not sure if there's a way to change the scope of a variable in matlab. You can define them dynamically using eval, but that still won't get us past the scope problem.
You have two options: if the names mater to you, you could put the imported tables in a struct, akin to what import does; or, if you only care about the index, you could import them into an array (perhaps multidimensional).
For the former you could do something like
function [datasheet] = imp_vrad(prefix,numslits)
%[data] = imp_vrad(prefix,numslits)
% imports data with filenames <prefix>_slit_<##>.txt
% into a struct with labels <prefix>_slit_<##>
% here ## starts from '01' and goes to 'numslits'
% FILES MUST BE IN WORKING DIRECTORY!
%
datasheet = struct();
for currslit=1:numslits
dataname = sprintf('%s_slit_%02d',prefix,currslit);
filename = [dataname,'.txt'];
disp(['importing ' filename ' as ' data])
data = importdata(filename); %imports the data
datasheet.(dataname) = data;
end
end