Matlab: function on multiple files - matlab

I want to read all wav files containing in a folder, for each file I perform a function.
The result of this function is a number. I want save several results in a file txt.
This is my code:
dirMask = 'folder\*.wav';
wavRoot = fileparts(dirMask);
Files=dir(dirMask);
x = [];
for k=1:length(Files)
FileNames = fullfile(wavRoot, Files(k).name)
nomi=FileNames;
[s,fs] = audioread(FileNames);
a = function(s, fs);
x=a;
end
fid = fopen('file.txt','wt');
fprintf(fid,'%f\n',x);
fclose(fid);
This code doesn't work. How can I do this?

I rearranged things a bit. I wasn't entirely positive of the original intent but I think this is what you were trying to achieve:
dirMask = 'folder\*.wav';
Files = dir(dirMask);
fid = fopen('file.txt','wt');
for k=1:length(Files)
FileName = [ Files(k).folder '\' Files(k).name ]
[s,fs] = audioread(FileName);
% functions named function is a bad idea as it is keyword protected
x = myFunction(s,fs);
fprintf(fid,'%f\n',x);
end
fclose(fid);

Related

Matlab save table with different file names in different files

I'm trying to read different files (txt) using a datastore and readtable in order to parse them and write them into a .mat file.
I'm using ds = datastore('*.txt').Files to get all the file names in a directory, then with a for loop I iterate through all the different files and I save them with different names.
However when I import the file in matlab they have all the same table name (dat).
Here's the code:
ds = datastore('*.txt');
fnames = ds.Files;
l = length(fnames);
for i = 1:l
dat = readtable(fnames{i}, 'Delimiter', '\t');
dat.Properties.VariableNames(1:2) = {'rpm', 'p_coll'};
dat = removevars(dat{i},20:width(dat));
save([fnames{i} '.mat'],'dat');
end
I tried using an array of dat but it didn't work. Any ideas?
As Sardar said there is no point in storing your data in L different variables. If you have to do so, there probably is a bigger problem in your program design. You'd better describe why you need that.
As an alternative, you can load those files in a single cell array:
L = 10;
for ii =1:L
dat = 2*ii;
fn = sprintf('dat%d.mat', ii);
save(fn, 'dat');
end
dats = cell(L, 1);
for ii=1:L
fn = sprintf('dat%d.mat', ii);
load(fn);
dats{ii} = dat;
end
Another option is to lad them in a struct:
dats = struct();
for ii=1:L
fn = sprintf('dat%d.mat', ii);
load(fn);
dats.(sprintf('dat%d', ii)) = dat;
end
I do not see any advantage in this method compared to cell array, but it's kind of funny.
Finally, if you really have a reason to store data in multiple variables, you can use eval:
for ii =1:L
dat = ii^2;
eval(sprintf('dat%d=dat;', ii));
fn = sprintf('dat%d.mat', ii);
save(fn, sprintf('dat%d', ii));
end
for ii=1:L
fn = sprintf('dat%d.mat', ii);
load(fn);
end

read multiple files in from a directoryusing matlab

How can read multiple files in from a directory using matlab? Can someone please help correct my code below:
files =dir(fullfile(directory_path,'*.dat'));
numfiles = length('*.dat');
mydat = cell(1, numfiles);
for k = 1:numfiles
mydata{k} = fopen([directory_path,files(k).name]);
values=textscan(mydata{k},'%s','delimiter','\n');
fclose(fid);
%fprintf(values)
....do something with values.....
end
.dat files are just many rows and single column of strings that need to be read in a loop and processed further.
Thanks
fopen gives file pointer, which you save to mydata{k}, and try to release by fclose(fid). There is no fid, so it doesn't work.
What you should do is replace mydata{k} with fid. And probably values by mydata{k}.
The other bug is in numfiles = .... You will always have numfiles = 5, as there are 5 characters in the '*.dat'.
numfiles = length(files);
would be better, although you would also count directories. Check one of the other questions how to solve this.
Thanks Zizy Archer.
I solved the problem this way:
files =dir(fullfile(directory_path,'*.dat'));
numfiles = length(files);
for k = 1:numfiles
textFileName = [directory_path,files(k).name]
fid = fopen(textFileName, 'r');
textData = textscan(fid,'%s','delimiter','\n');
fclose(fid);
data = textData{:,1}
end

Matlab: func2str from a function in a m-file

In a main m-file I have
conformal = maketform('custom', 2, 2, [], #conformalInverse_0001, []);
used in imtransform that refers to the function defined in conformalInverse_0001.m:
function U = conformalInverse_0001(X, ~)
%#codegen
U = [zeros(size(X))];
Z = complex(X(:,1),X(:,2));
W = 1./(4.*Z.^2-1);
U(:,2) = imag(W);
U(:,1) = real(W);
How can I get the string '1./(4.*Z.^2-1)' in the main program?
I found a way to solve it, but it's not so elegant...
Assume conformalInverse_0001.m is a file in your folder.
You can parse the file as a text file, and search for your formula.
Example:
Assume you know the location is 5'th line in file, and start with W =.
You can use something like the following code to read '1./(4.*Z.^2-1)' in the main program:
%Open file for reading.
fid = fopen('conformalInverse_0001.m', 'r');
%Read 5 lines.
s = textscan(fid, '%s', 5, 'delimiter', '\n');
fclose(fid);
%Get the 5'th line.
s = s{1}(5);
%Convert cell array to string.
s = s{1};
%Get characters from the 5'th character to one char before end of string.
s = s(5:end-1)
Result: s = 1./(4.*Z.^2-1)
You can check textscan documentation for finding more elegant solution.
I'm not sure I fully understand the problem here, but what about adding into your conformalInverse_0001 function something like:
str = '1./(4.*Z.^2-1)';
save('temp_str','str') % or whatever data that you want to save from it
and then adding in your main file:
load('str.mat')% or you can use 'impordata'
where you want to extract it.
I have hacked two solutions with textscan: first knowing the line number and second searching the line that starts with substring 'W = '
% read line line_num = 5 and process string
f_id = fopen(conformalInverse_m_path);
conformalInverse_cell = textscan(f_id,'%s','delimiter','\n'); %disp(conformalInverse_cell); % {68×1 cell}
func_string = conformalInverse_cell{1}{line_num}; disp(func_string); % W = 1./(4.*Z.^2-1); OK
func_string_2=func_string(5:end-1); disp(func_string_2); % 1./(4.*Z.^2-1); OK
% read first line that starts with substring 'W = ' and process string
W_string = 'W = ';
for i=1:100
func_string = conformalInverse_cell{1}{i};
Firt4=func_string(1:4); %disp(['i = ', num2str(i), ': First4 = ', Firt4]);
if strcmp(Firt4,W_string) == 1; line_nr = i; break; end;
end
func_string_2 = conformalInverse_cell{1}{line_nr};
func_string_3=func_string_2(5:end-1);

Matlab Input/output of Several Files

I do matlab operation with two data file whose entries are complex numbers. For example,
fName = '1corr.txt';
f = dlmread('1EA.txt',',');
fid = fopen(fName);
tline = '';
Then I do matrix and other operations between these two files and write my output which I call 'modTrace' as:
modTrace
fileID = fopen('1out.txt','w');
v = [(0:(numel(modTrace)-1)).' real(modTrace(:)) ].';
fprintf(fileID,'%d %e\n',v);
The question is, if I have for example 100 pairs of such data files, like (2corr.txt, 2EA.txt), ....(50corr.txt, 50EA.txt) how can I generalize the input files and how to write all the output files at a time?
First of all, use sprintf to get your variable names depending on the current index.
corrName=sprintf('%dcorr.txt',idx);
EAName=sprintf('%dEA.txt',idx);
outName=sprintf('%dout.txt',idx);
This way, you have one variable (idx) which has to be changed.
Finally put everything into a loop:
n=100
for idx=1:n
corrName=sprintf('%dcorr.txt',idx);
EAName=sprintf('%dEA.txt',idx);
outName=sprintf('%dout.txt',idx);
f = dlmread(EAName,',');
fid = fopen(corrName);
tline = '';
modTrace
fileID = fopen(outName,'w');
v = [(0:(numel(modTrace)-1)).' real(modTrace(:)) ].';
fprintf(fileID,'%d %e\n',v);
end
Instead of hardcoding the number 100, you could also use n=numel(dir('*EA.txt')). It count's the files ending with EA.txt

how to save files in a loop in Matlab?

I have some geotif files and I am trying to create a mosaic out of them. I have tried to put the images beside each other first in a row and then tried to join the in columns and have the final mosaic. I would like to have the output file with the save number of the loop (outimage1,outimage2,..). I would like to know how should I introduce the output file with the sequence of the loop number.
I would be happy if someone help me find my mistake in the following code.
close all;
clear all;
clc;
path = 'E:\MATLAB\...\tifs\';
path2 = 'E:\MATLAB\...\tifs\out\';
matfiles = dir(fullfile('E:', 'MATLAB',...,'tifs','*.tif'));
files = {matfiles.name};
lf=length(files);
image_row = [];
for L=1:11
for k=1:14:lf
fname = matfiles(k).name;
fullname = horzcat (path,fname);
infile = imread (fullname);
image_row= [image_row,infile];
[~, ~, ext] = fileparts(fname);
outimage = fullfile( path2, sprintf('outimage%d%s', L, ext) );
imwrite(image_row,outimage);
end
end
Yours assistant is highly appreciated.
I am not familiar with a matlab syntax k. format(fname).
If you want to do string formatting in Matlab - read this first.
A solution for your problem might be
outimage = fullfile( path2, sprintf('outimage_%03d_%s', k, fname ) );
EDIT:
following comment by OP, get the file format (tif):
[~, ~, ext] = fileparts(fname);
outimage = fullfile( path2, sprintf('outimage%d.%s',ext) );