how to save files in a loop in Matlab? - 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) );

Related

Matlab: Error using readtable (line 216) Input must be a row vector of characters or string scalar

I gave the error Error using readtable (line 216) Input must be a row vector of characters or string scalar when I tried to run this code in Matlab:
clear
close all
clc
D = 'C:\Users\Behzad\Desktop\New folder (2)';
filePattern = fullfile(D, '*.xlsx');
file = dir(filePattern);
x={};
for k = 1 : numel(file)
baseFileName = file(k).name;
fullFileName = fullfile(D, baseFileName);
x{k} = readtable(fullFileName);
fprintf('read file %s\n', fullFileName);
end
% allDates should be out of the loop because it's not necessary to be in the loop
dt1 = datetime([1982 01 01]);
dt2 = datetime([2018 12 31]);
allDates = (dt1 : calmonths(1) : dt2).';
allDates.Format = 'MM/dd/yyyy';
% 1) pre-allocate a cell array that will store
% your tables (see note #3)
T2 = cell(size(x)); % this should work, I don't know what x is
% the x is xlsx files and have different sizes, so I think it should be in
% a loop?
% creating loop
for idx = 1:numel(x)
T = readtable(x{idx});
% 2) This line should probably be T = readtable(x(idx));
sort = sortrows(T, 8);
selected_table = sort (:, 8:9);
tempTable = table(allDates(~ismember(allDates,selected_table.data)), NaN(sum(~ismember(allDates,selected_table.data)),size(selected_table,2)-1),'VariableNames',selected_table.Properties.VariableNames);
T2 = outerjoin(sort,tempTable,'MergeKeys', 1);
% 3) You're overwriting the variabe T2 on each iteration of the i-loop.
% to save each table, do this
T2{idx} = fillmissing(T2, 'next', 'DataVariables', {'lat', 'lon', 'station_elevation'});
end
the x is each xlsx file from the first loop. my xlsx file has a different column and row size. I want to make the second loop process for all my xlsx files in the directory.
did you know what is the problem? and how to fix it?
Readtable has one input argument, a filename. It returns a table. In your code you have the following:
x{k} = readtable(fullFileName);
All fine, you are reading the tables and storing the contents in x. Later in your code you continue with:
T = readtable(x{idx});
You already read the table, what you wrote is basically T = readtable(readtable(fullFileName)). Just use T=x{idx}

Matlab: function on multiple files

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);

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);

Looping VideoReader in Matlab for processing

I've looked everywhere and I still cannot seem to successfully loop MATLAB's videoreader. I am trying to use MATLAB to process videos and convert them to saved image sequences which I can analyze by binary pixel properties for areas and such. I'm really new to MATLAB so any help would most certainly help.
Here is my code thus far for the image sequence creation. Also this is in R2015a.
function VideoToImageSequence(dirname,doall)
% load up the set of global variables
global settings
inpath = [settings.inpath, '\' , settings.dirname, '\'];
outpath = inpath;
%list of files
list = dir([inpath, '\*.avi']);
N =length(list);
display(['Found ', mat2str(N), ' movies in ', inpath]);
%Main converter
for i= 1:N
rootname{i} = list(i).name(1:end-4);
savefile = [rootname{i}, '.mat'];
if exist([inpath, savefile], 'file') && doall==0
display(['Found analyzed file ', savefile, ' .... skipping']);
else
%Directory
addpath(genpath([settings.inpath,'\', settings.dirname,'\' ,rootname{i}]));
workingDir = [settings.inpath,'\' , settings.dirname, '\' , rootname(i)];
cd([settings.inpath, '\', settings.dirname, '\'])
filename= rootname(i) ;
VideoFile = VideoReader(filename) ;
ii = 1;
%Spits out image sequence
while hasFrame(VideoFile(i))
img = readFrame(VideoFile(i));
filename = [sprintf('%03d',ii) '.jpg'];
fullname = fullfile(workingDir,'images',filename);
imwrite(img,fullname) % Write out to a JPEG file (img1.jpg, img2.jpg, etc.)
ii = ii+1;
end
end
end
Any help you can give would be awesome! Thanks.