Error by using eval in function in MATLAB - 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

Related

Problems using Matlab function eps2pdf

I have a Matlab script where I produce a figure, and then create an eps file in my current directory using the command
print('myFile','-depsc'). Immediately following, I have: mypdf = eps2pdf('myFile').
I get the error message that 'Error while creating temporary eps file: ..... cannot be accessed or does not exist'.
Has anyone had a similar problem? Any suggestions what I might be doing wrong? I'm using Ubuntu and Matlab 2017a.
Here is an example code that I type into the command line. I get the error message which I stated above.
figure()
plot(linspace(1,100),linspace(1,100)) %Simple line
print('my_plot','-depsc') %Create eps file.
mypdf = eps2pdf('my_plot'); %Should produce mypdf in my current directory.
<error message prints>
This isn't a standard function. If you read the function you will see errStr that it returns for this.
function [ok,errStr] = read_epsfilecontent( epsFile )
% Reads the content of the eps file into epsFileContent
global epsFileContent
ok = 0;
errStr = [];
fh = fopen(epsFile,'r');
if fh == -1
errStr = ['File: ' epsFile ' cannot be accessed or does not exist'];
return
end
Then we figure out when fopen returns -1
fileID = fopen(filename) opens the file, filename, for binary read
access, and returns an integer file identifier equal to or greater
than 3. MATLABĀ® reserves file identifiers 0, 1, and 2 for standard
input, standard output (the screen), and standard error, respectively.
If fopen cannot open the file, then fileID is -1.
Which means please post some of your code so we can figure out why it cannot open your file.
Edit: After some work around and it wasn't necessary to download the code this is how I solved your problem. There is another implementation called eps2xxx
While running your code I received this error
Error while creating temporary eps file: *.eps - File:
C:\Users\Ryan\Documents\MATLAB*.eps cannot be accessed or does not
exist
Which lead me to the information in the documentation here.
% Create tmp file,...
[ok,errStr] = create_tmpepsfile(source,tmpFile,orientation);
if ~ok
status = ['Error while creating temporary eps file: ' epsFile ' - ' errStr];
if nargout, result = 1; end;
if nargout > 1, msg = status; else, disp(status); end;
And I read you needed GhostScript, I wasn't sure if I had this anyways. I downloaded it and gave the full pathway to GS like the following.
figure()
fullgspath = 'C:\Program Files\gs\gs9.23\bin\gswin64c.exe';
plot(linspace(1,100),linspace(1,100)); %Simple line
print('my_plot','-depsc');
eps2xxx('my_plot.eps',{'pdf'},fullgspath);
which created your nice little pdf here.

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

How to fix error: "A(I): index out of bounds; value 1 out of bound 0"

So I made this function, but I don't know why I'm getting this error. How can I fix it?
error: LOADC: A(I): index out of bounds; value 1 out of bound 0
error: called from
LOADC at line 15 column 13
function res=LOADC(url)
[nomeFicheiro,sucesso]= urlwrite(url,'Composicoes.txt');
ficheiro=fopen(nomeFicheiro,'r');
fgetl(ficheiro);
nLinhas=0;
while (fgets(ficheiro) ~= -1)
nLinhas = nLinhas+1;
end
for i=2:nLinhas
linha=fgetl(ficheiro);
pontovirgula=findstr(linha,';');
Material=linha(1:pontovirgula(1)-1);
for n=1:2:length(pontovirgula)
ElemX=linha(pontovirgula(n)+1:pontovirgula(n+1)-1);
PercentX=linha(pontovirgula(n+1)+1:pontovirgula(n+2)-1);
end
end
fclose(ficheiro);
res=Composicoes;
end
The immediate is you're trying to access a value within an empty array (which has no values in it).
The reason that this is happening is that you read your entire file inside of your first while loop which places the file pointer at the end of the file. Then (without resetting the file pointer), you try to read it line by line in the for loop. Since the file pointer is at the end of the file already, fgetl will always return an empty array ([]) so when you start trying to work with it, you get the indexing error that you've shown.
The solution is one of two options:
Call frewind(ficheiro) before the for loop to reset the file pointer to the beginning of the file so that you can successfully read each line.
Come up with a better way to parse your file rather than looping through the whole file for the sole purpose of counting the number of lines in the file.
If you post some of the file contents we can likely provide you with a better way to parse the file in one or two lines of code.
Update
Also if you look at this line, n goes all the way to the end of pontovirgula.
for n = 1:2:length(pontovirgula)
But then you try to access 1 and 2 past the end of the array
pontovirgula(n+1)
pontovirgula(n+2)
This is going to cause issues for sure. Try only looping until 2 from the end instead.
for n = 1:2:(numel(pontovirgula) - 2)
Update 2
Given that you have posted the file contents, here is an alternate way to parse the file.
fid = fopen('filename.txt', 'rt');
lines = textscan(fid, '%s', 'HeaderLines', 1);
fclose(fid);
% For each line we want to get the reference off of the front
parts = regexp(lines{1}, ';', 'split');
materials = cell(1, numel(parts));
elements = cell(1, numel(parts));
percentages = cell(1, numel(parts));
for k = 1:numel(parts)
% Remove the last empty blank
parts{k}(end) = [];
% Get the material (the first element)
materials{k} = parts{k}{1};
% Get the elements
elements{k} = parts{k}(2:2:end);
% Get the percents
percents{k} = parts{k}(3:2:end);
end
Check the length of linha, and the values of pontovirgula that you are using to index into linha.

trying to open a file in loop 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

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