Problem using cd in MATLAB function
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Rhiannon Vieceli
el 27 de Jul. de 2015
Comentada: Rhiannon Vieceli
el 29 de Jul. de 2015
Hi, I'm writing a MATLAB function that needs to change directories, but I keep getting this error:
Error in GetStations (line 5)
home = cd;
Here is part of my function:
function [Stations,NumStations] = GetStations(NLat,SLat,ELon,WLon)
% This function searches a list of seismic stations for those within the geographic box specified by the input latitudes and longitudes.
home = cd; % Where I'm currently working
% Go to where the seismic station list is saved:
cd('C:\Users\User\Desktop\Research\MATLABFunctions');
StationList = fopen('Stations.txt'); % Open text file
% Read file, skip first line:
AllStations = textscan(StationList, '%s %s %f %f','headerlines', 1);
fclose(StationList); % Close text file
cd(home); % Go back to where I'm currently working
1 comentario
Respuesta aceptada
Stephen23
el 27 de Jul. de 2015
Editada: Stephen23
el 28 de Jul. de 2015
The syntax
home = cd;
is possibly not valid: it is not covered by the online documentation. The best solution is to avoid using cd for this anyway: using cd makes your code slow, fragile and difficult to debug. A faster, neater and much more versatile solution is to pass filepaths instead. So remove all of those cd's, and try this:
my_path = 'C:\Users\User\Desktop\Research\MATLABFunctions';
my_file = 'Stations.txt';
my_full = fullfile(my_path,my_file);
%
fid = fopen(my_full,'rt');
C = textscan(fid, '%s%s%f%f', 'headerlines',1);
fclose(fid);
7 comentarios
Stephen23
el 28 de Jul. de 2015
Editada: Stephen23
el 28 de Jul. de 2015
The problem is not the first line of code (whatever it may be), but the fact that within your function the outputs Stations and NumStations have not been defined. If you are calling the function with these outputs but they are not defined inside the function then this causes an error to be thrown. One simple solution is to temporarily define some placeholder values at the beginning of the function, and remove them later when you calculate the real values:
Stations = [];
NumStations = [];
Más respuestas (0)
Ver también
Categorías
Más información sobre Geographic Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!