calling an external program in matlab in a loop - matlab

I have installed Matlab 2014 in Ubuntu. My problem:
I build several input files for another program, Quantum Espresso, in Matlab. Now I should pass these files to Quantum Espresso using matlab command line. Now I know I can do this using Linux Terminal, but my way of solving my problem has reached the point that my only option is 'calling Quantum Espresso from matlab'. One single call is actually easy:
! installation/folder/espresso-5.3.0/bin/pw.x < inputfile > outputfile
The problem is I have several input files named like 1name.in 1name.in ... . So this repeated calls should be done in a loop. But how?
I have tried:
the shell script for looping though the files. I added that extra '!' to each line of the script but it doesn't work.
I also tried to write a loop like this :
for i = 1:N
prefix = int2str(i);
fuloutname = [prefix 'name' '.' 'out'];
fulinname = [prefix 'name' '.' 'in'];
! adress/espresso-5.3.0/bin/pw.x < fulinname > fuloutname ;
end
In which 'N' in number of my input files. Clearly running this means you are passing a file nemaed 'fulinname' not 1name.in and will result in an output file named 'fuloutname'
I also tried to do it as you normally load various files in a loop but it also did not work
Please help me.

You should use the unix function:
for i = 1:N
prefix = int2str(i);
fuloutname = [prefix 'name' '.' 'out'];
fulinname = [prefix 'name' '.' 'in'];
mycommand = ['adress/espresso-5.3.0/bin/pw.x < ',fulinname,' > ',fuloutname];
unix(mycommand);
%system(mycommand); %will give you the same, result and this function is cross-platform
end

Related

While running Compiled MatLab from console window, prompt returns immediately while app is still running

I have compiled my simple MatLab function so I can run it from a Windows console as a command line app. After I enter the command and its single argument, the prompt returns immediately even though the command is still running, as if running in the background.
Can someone tell me why this happens and how do I stop it? I'd like it to behave like a normal application and not return to the prompt until complete.
EDIT: Sorry I didn't post the code previously, I figured I was making a common mistake and would get a quick answer. Anyway, here it is.
It translates a .mat file to a .csv file and then runs another console command via "system" to perform a quick edit on the resulting .csv file. Several minutes of IO but not much else.
I've never compiled MatLab before so probably something simple, I hope.
function WriteMatToCSV( inFile, overWrite )
if ~exist(inFile, 'file')
fprintf('Error File not found: %s\n',inFile);
return;
end
overWriteExisting = 1;
if exist('overWrite','var')
overWriteExisting = overWrite;
end
% Change file extension
outFile = strrep( inFile, '.mat','.csv');
fprintf('In : %s\n',inFile);
fprintf('Out: %s\n',outFile);
% Overwrite if exists?
if exist(outFile, 'file')
if ~overWriteExisting
fprintf('Error File exists: %s\n',outFile);
return;
end
end
% Get variable name in the file
matObj = matfile(inFile);
info = whos(matObj);
name = info.name;
fprintf('Found variable: %s\n',name);
% Load the variable from the file
fprintf('Loading mat...\n');
load(inFile);
% Write the variable to .csv file
fprintf('Writing csv...\n');
export(eval(name),'File',outFile','Delimiter',',');
fprintf('Rewriting to remove MatLab bits...\n');
command = 'RewriteMatLabCSV';
command = [command ' ' outFile];
[status,cmdout] = system(command,'-echo');
fprintf(cmdout);
fprintf('Done\n');
end

run script command in Matlab

I am running a script in another directory.
Assume I have the following code:
arr = [10;20;30];
run(script); % script= path to the script file + scriptfile.mat ..
x = arr(2);
It gave me the following error:
Undefined function 'arr' for input arguments of type 'double'.
After debugging the code, I found that run(script) .. run the script and then clear all variables .. such as arr.
Is there any way to make run command doesn't clear all variables..
Edit: the following is the original code..
xValues =[2;4;6];
yValues =[10;15;20;30;40];
for var1 =1:size(xValues,1)
results =[];
for var2 =1: size(yValues,1)
run(strcat('C:\Users\as\Desktop\study',num2str(xValues(var1)),'folder\',num2str(yValues(var2)),'folder\file1.m'));
results(var2,1) = yValues(var2);
end
end
Thanks,
Here is an example, erase clear command in your script file:
testing.m
arr = [10;20;30];
run('ScriptFile.m')
x = arr(2);
ScriptFile.m
disp('Hello World');
Command Window
Hello World
After the implementation x holds number 20.
It is clear all inside your script doing the mess I believe.
As for how to avoid it:
Simply remove it. This is generally the easiest and best solution.
Write file to the disk, run script, load from disk. You need a hardcoded file name.
Create "data_holding_function" that has persistent cell array, you load your data there and then restore it after script. You can make the function perform both loading (when you have some input) and unloading (when you don't).

Matlab Function fails due to : 'Error using Eval', works fine when used in Command Window

When plotting data from a .mat file, if I enter the lines from a script one-by-one, it works fine... but when I try running the script, it fails.
function Test (filename)
varname = load (filename) %or load filename
matObj = matfile(filename);
varlist = who (matObj); %or varlist = fieldnames (varname)
field1 = eval ( varlist {1} )
field2 = eval ( varlist {2} )
x1 = field1.x_values.start_value:field1.x_values.increment:field1.x_values.increment*field1.x_values.number_of_values;
x2 = field2.x_values.start_value:field2.x_values.increment:field2.x_values.increment*field2.x_values.number_of_values;
figure
hold all
%Support for yyaxis left/right not avaiable, so use plotyy
plotyy (x1, field1.y_values.values, x2, field2.y_values.values)
end
When I invoke the script (Test ('1.mat')), Matlab shows an error on the field1 = line :
Error using eval
Undefined function or variable 'Signal'.
The 'Signal' is one of the data set names in the 1.mat file.
Interestingly, when I run each line by itself in the same order from the command window, I don't get any error and the plot displays. I verified that the current path has the script and the 1.mat file, but I can't figure out why it complains about the eval when run from the script.
The issue is because your matObj is a *.mat file which contains the variable named Signal. You never load the file in your function (using load) but instead you assign a matfile object to matObj. To read a variable from this do not use eval (ever), rather you just want to use dynamic fields referencing into the matfile object.
field1 = matObj.(varlist{1});
field2 = matObj.(varlist{2});
In general though, you should probably know the name of the variables you're trying to load from the file rather than simply using the first two variables you find with who. If that's the case, just use them directly.
field1 = matObj.Signal;
The reason that your code likely worked in the command window is because at some point you probably loaded the .mat file into the command window workspace using load which would have loaded all it's contents (including Signal) into the workspace.
load('filename.mat')
Also as a bit of a nit-pick. You don't have a script you have a function (you have a function definition at the top). This has huge ramifications for diagnosing your problem. You cannot test a function by copy/pasting stuff into the command window due to the different scope of a function.

matlab pathfinder - problems with understanding

I got an matlab-function which shall find files by returning their path. This is exactly what i need for my purpose. The problem is that the code is written by me. So I do not quite understand how this function works, especially the inputs which I do not understand.
I hope u can help me to understand this function.
Best regards!
Here is the code:
function B = getAllPaths(basepath, name)
temp=genpath(basepath);
A=regexp(temp,';','split');
j=1;
for i=1:length(A)-1
pfad=cell2mat(A(i));
if(exist([pfad name],'file'))
B(j)=cellstr(pfad);
j=j+1;
end
end
clear A i name pfad temp
I would write that function as
%// Get all child directories of 'basepath' that contain a file named 'name'
function B = getAllPaths(basepath, name)
A = regexp(genpath(basepath), ';', 'split');
B = A(cellfun(#(x) exist([x name],'file') ~= 0, A));
end
or
%// Get all child directories of 'basepath' that contain a file named 'name'
function B = getAllPaths(basepath, name)
if ispc
[OK,dirs] = system(['cd "' basepath '" && dir /s /b "' name '"']);
elseif isunix
[OK,dirs] = system(['find "' basepath '" -type f -name "' name '"']);
end
if ~OK
B = cellfun(#fileparts, cellstr(b), 'UniformOutput', false);
else
B = {};
end
end
MATLAB is interactive! So interact with it! Use any typical basepath and name and execute your function in the command window, line by line, displaying the output each time. Try to change a few commands and see how that changes the output. Type help cellfun and Read, Learn, Master. Click on links in see also [...] at the bottom of each help, even though you think you know it. Type edit cell2mat and Read, Learn, Master, etc. etc. etc.
Understanding a language takes practice, not a bunch of answers from some forum.
Thank you very much for your advice. I know it takes time to learn how to program. Im still examining this code but I have not understand it yet completely.
I got a problem with the line:
exist([pfad name],'file')
E.g. When I try to find "xyz" a file in folder "ABC" what must be in "name"? I write "ABC" in name but then it does net work.
Kind regards!

Piping gdalinfo.exe to matlab/octave with system() does not return any output

I am trying to use the system() function to pipe the output of the gdalinfo (version 1.10 x64) utility directly to Matlab/Octave. The function consistently returns status=0, but does not return any output. For example:
[status output] = system('"C:\Program Files\GDAL\gdalinfo.exe" "E:\DATA\image.tif"')
will only return:
status =
0
output =
''
Any idea why no output is returned?
It appears there is something strange about `gdalinfo.exe'. Several people have reported difficulty piping the output of the program to a textfile - see for example http://osgeo-org.1560.x6.nabble.com/GDALINFO-cannot-pipe-to-text-file-td3747928.html
So the first test would be - can you do something like this:
"C:\Program Files\GDAL\gdalinfo.exe" "E:\DATA\image.tif" > myFile.txt
and see whether the file is created and has any content? If it doesn't, it may be that the program is using a different way to produce output (for example, using stderr instead of stdout). If it is possible to get data into a text file but not directly to matlab, I suppose a workaround would be to write to file, then read that file in separately:
tempFile = tempname; % handy built in function to create temporary file name
execCmd = '"C:\Program Files\GDAL\gdalinfo.exe ';
targetFile = '"E:\DATA\image.tif"';
status = system([execCmd targetFile ' > ' tempFile]);
output = textread( tempFile, '%s' );
system(['del ' tempFile);
Now the output variable will be a cell array with one cell per line in the input file.
This works on my Windows machine if I am in the Octave directory:
[status output] = system('ls bin')
I was having the same issue trying to pipe the output from within C#. It turns out that the ECW plugin breaks the capability (I don't know how). If this plugin is not crucial to you, go into the plugins directory and delete gdal_ECWJP2ECW.dll. You should be able to use '>' and other stuff to dump your output to a file.