trying to open a file in loop matlab - matlab

I have been trying to open files in a loop. I did this:
file='';
loc='F:\UT_timestep\';
name='time_';
gridext='.grd';
for i={'a','b','c'}
file=strcat(loc,name,i,gridext);
f=fopen(file,'rb');
...
fclose(f);
end
but it gives this error :
Error using fopen
First input must be a file name of type char, or a file identifier of type double.
Error in script_UT (line 28)
f=fopen(file,'rb');
I am not able to understand why this is giving error. Please help.

This is because file is a cell array of 1 element. You want the actual string inside the cell array, not the actual cell itself. Do this:
file='';
loc='F:\UT_timestep\';
name='time_';
gridext='.grd';
for i={'a','b','c'}
file=strcat(loc,name,i,gridext);
f=fopen(file{1},'rb'); %// Change
...
fclose(f);
end

Related

Error by using eval in function in MATLAB

I have the following MATLAB function:
function getDBLfileL1(pathInput,Name_file,folderName)
DBL_files=dir([pathInput,'/*.DBL']); %get DBL files
fprintf('Reading DBL files ... ')
for i = 1:length(DBL_files) %loop through all DBL files
[HDR, CS]=Cryo_L1b_read([pathInput,'/',DBL_files(i).name]); %read data with ESA's Cryo_L1_read function
Coord{i}.LAT_20Hz=CS.GEO.LAT; %store values to struct
Coord{i}.LON_20Hz=CS.GEO.LON;
Coord{i}.BoundingBox_StartLATLON_StopLATLON=[HDR.START_LAT*10^-6,HDR.START_LONG*10^-6,HDR.STOP_LAT*10^-6,HDR.STOP_LONG*10^-6];
Coord{i}.FileName=[pathInput,'/',DBL_files(i).name];
end
eval([Name_file '= Coord;']);
save(['output/',folderName,'/',Name_file,'.mat'],Name_file,'-v7.3')
fprintf('done\n')
end
And it is called in the following:
getDBLfileL1(pathInput,[folderNames{i},'_',folderNames1{j}],folderNames{i}); %read Data from DBL file
The Value of Name_file is '2011_01', and I get the following error:
eval([Name_file])
Error: Invalid text character. Check for unsupported symbol, invisible character, or pasting of non-ASCII characters.
Does anyone know why this error occur or how I can change the file, that I can replace the eval() function?
Thanks a lot in advance!
If I got it right, you are trying to evaluate '2011_01= Coord;' , which means that you are assigning Coord into a variable called 2011_01, and variable names cannot start with numbers

'pie' function in MATLAB gives "undefined function 'cos'" error

I wrote a function, wins_plot, to read the scoreboard from a file and store the player's name, number of plays, wins, & losses. I stored all those using struct. I loop over the file, store each line in line, textscan for everything I need from line, and then iterate i (initially == 1) as I go to expand my array of structures. A snippet from the code to represent what I am saying:
c = textscan(line, '%s %s %d %d %d');
player(i).firstName = c{1};
player(i).lastName = c{2};
player(i).plays = c{3};
player(i).wins = c{4};
player(i).losses = c{5};
After all the file has been scanned and stored, I then write this code to extract the number of wins of each player and store it in X and then finally use the pie function to represent the values in X
for n=1:(i-1)
X(n) = player(n).wins;
end
pie(X);
I get a wall of error after:
Undefined function 'cos' for input arguments of type 'int32'.
Error in pol2cart (line 22) x = r.*cos(th);
Error in pie (line 99)
[xtext,ytext] = pol2cart(theta0 + x(i)*pi,1.2);
Error in wins_plot (line 30) pie(X);
I have no clue what might be wrong. Any help would be greatly appreciated. Please keep in mind that I only just started learning MATLAB today so my knowledge of it is very limited (and I have R2013a). Thank you in advance!
The numbers got read as int32, but when you call pie, it requires them to be double to do the computation. So, when you call pie, try casting the values to double. Try this,
pie(double(X));

Matlab variable which stores the name of the mfile and line number

For debugging purpose, I want to print out the name of the m-file and the line number so that, when something goes off, it says something like
Error at 197th line of run.m
Given that Matlab displays an error message of this type, there must be a solution.
How can I do this?
===========Follow-up question==============
Thank you! But I got a follow-up question.
I have main.m which is the main m-file and main.m calls lower.m
I wrote
info = dbstack()
and
try
error('Toto')
catch ME
ME.stack
end
to the main.m. Then Matlab displays
info =
file: 'main.m'
name: 'main'
line: 15
ans =
file: 'C:\Users\account1\Google Drive\1AAA-RA\11HHJK(O…'
name: 'main'
line: 18
However, when I write dbstack and try-catch thing to lower.m, then Matlab does not display any exact information.
I ran the main.m and main.m called the lower level m-file but it doesn't display any information.
info =
2x1 struct array with fields:
file
name
line
ans =
2x1 struct array with fields:
file
name
line
What should I do to make it display every file, name, line information?
Ideally, Matlab will display the information of both main.m and lower.m like the following:
file1: 'main.m'
name1: 'main'
line1: 15
file2: 'lower.m'
name2: 'lower'
line2: 6
Is this possible?
You can use the Matlab Exception object. The line information is contained in the 'stack' property.
Example create a 'test.m' script:
try
error('Toto')
catch ME
ME.stack
end
Output of command window is:
>> test
ans =
file: 'D:\MATLAB\Sandboxes\AVLab\test.m'
name: 'test'
line: 2
Or without a try/catch you can use MException.last.
See documentation link http://www.mathworks.com/help/matlab/matlab_prog/capture-information-about-errors.html
info = dbstack();
% info is now a struct that has 3 fields
% info.file
% is a string containing the file name in which the function appears.
% info.name
% is a string containing the name of the function within the file.
% info.line
% is the line number on which dbstack was called
MATLAB's error function will automatically display the filename and line number.
function [ ] = wsgefiow9ey( )
n = 7;
if n > 1
msg = 'Error: n is too big.';
error(msg)
end % if
end % function definition
click here to see console output resulting from call to MATLAB error function

Create a blank text file from within a function in Matlab

I wnat to create a function:
function[check]=createFile(filename, matrix)
Where I create a blank text file with the name 'filename'.
Where later in the function inputs from 'matrix' can be put in and stored.
2 question:
1)How do I create just a blank .txt file?
2)I've had some problem with this in somewhat simular functions, but is there an easy way to get rid of the need to write apostrophes in the arguments when calling the function?(i.e: createFile(name,matrix) instead of createFile('name',matrix)
to create the text file just use:
fid = fopen('filename.txt','w')
and there is no way to avoid the apostrophies 'filename.txt' - as matlab would try to call a function filename.txt which it wouldn't find.
for your function you can use
function [check] = createFile(filename, matrix)
% filename contains string!
fid = fopen(filename,'w')`
if exist('fid')
check = true;
else
check = false;
end
... write your matrix to file.
end
2) but is there an easy way to get rid of the need to write apostrophes in the arguments when calling the function?(i.e: createFile(name,matrix) instead of createFile('name',matrix)
Yes: you can type
createFile name matrix
after you have included this in createFile.m:
function createFile(name,matrix)
matrix=evalin('caller',matrix);

How to use "csvread" when the contents in the file have different formats?

I have a .csv file and the format is shown below:
mapping.csv
5188.40811,TMobileML
5131.40903,TMobileGregsapt
5119.40791,TMobileJonsapartment
5123.40762,TMobileRedhat
i want to store it in an 4 by 2 array, when i have a value such as 5131.40903(this is a 'string' not 'int'), i want to find the mapping relation which is TMobileGregsapt. But i meet two problem, the first is i can't use csvread('mapping.csv'), it will have some error:
(I think the problem might be 5131.40903 will be int when i use csvread, but TMobileGregsapt is a string...)
??? Error using ==> dlmread at 145
Mismatch between file and format string.
Trouble reading number from file (row 1, field 2) ==> TMobi
Error in ==> csvread at 52
m=dlmread(filename, ',', r, c);
even though i use dlmread('cell4.csv', ','), it still have some error:
??? Error using ==> dlmread at 145
Mismatch between file and format string.
Trouble reading number from file (row 1, field 2) ==> TMobi
The second problem is how can i finding the mapping relation in easy way, the naive method is using a forloop to find the position of array.
Thanks for your help:)
Both csvread and dlmread only work for numeric data. Something like this should work for you
out=textread('tmp.csv', '%s', 'whitespace',',');
nums = out(1:2:end);
strs = out(2:2:end);
% find index of 'TMobileGregsapt'
ind = find(strcmp('TMobileGregsapt',strs));
nums(ind)
Another answer that will work if you have mixed text/numeric csv but you either don't know what the format is, or it's heterogeneous, use the 'csv2cell' function from: http://www.mathworks.com/matlabcentral/fileexchange/20836-csv2cell
c = csv2cell( 'yourFile.csv', 'fromfile');
c(1, :) will give your headers and c(2:end, k) will give you each of the columns (sans the header), for k = 1:size(c, 2)