I can't get my code to run

1 view (last 30 days)
nicholas moran
nicholas moran on 13 Apr 2021
Edited: Jan on 14 Apr 2021
My code wont run and I keep getting:
Error using textread (line 162)
File not found.
Error in WeekImages (line 20)
[Seperation, Measured] = textread(data_path, '%f %f', 'headerlines', 1);
The Heading for my columns from my data are: Seperation Measured
My code is:
%% Program for reading data from txt file
clear all;
close all;
main_path = 'D:\UNI\2021\ERB302 Applied Geophysics\CodeImages\';
print_check = 1;
data_path= strcat(main_path, 'Data\Exercise_Image.txt');
scriptname = mfilename( 'fullpath' );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Open log file for writing
% fid = fopen( log_file, 'w+' );
fid = 1; %displays on the screen%
fprintf( fid, 'This is %s, running...\n', scriptname );
%% Read data file
[Seperation, Measured] = textread(data_path, '%f %f', 'headerlines', 1);

Answers (2)

Jan
Jan on 13 Apr 2021
Edited: Jan on 14 Apr 2021
The error message is clear: "File not found." There is no file called:
'D:\UNI\2021\ERB302 Applied Geophysics\CodeImages\Data\Exercise_Image.txt'
You have to fix the path or the file name.
[EDITED after reading new details in your answer]
The message is still the same: The file, you try to open, does not exist. If this happens, let Matlab show you the file name:
try
[Seperation, Measured] = textread(data_path, '%f %f', 'headerlines', 1);
catch ME
msg = sprintf('Cannot read file: %s\n%s\n', data_path, ME.message);
error('Your:Error:ID', '%s', msg);
end
You will see this folder:
'D:\UNI\2021\ERB302 Applied Geophysics\CodeImages\Data\Data\Exercise_Data.txt'
% ^^^^ ^^^^ twice...
Hints:
  • Use fullfile instead of strcat to concatenate paths. This cares for the correct file separators automatically.
  • Omit the brute clear all, close all header, because it is a shot in your knee. This wastes a lot of time without a profit. Teachers suggest to use it, because they have used it when they were students. But this is "cargo cult programming" - as WikiPedia for details.
  • Instead of hard codeing the path, you can determine the folder of the m-file dynamically:
Folder = fileparts(mfilename('fullpath'));
DataFolder = fullfile(Folder, 'Data');

nicholas moran
nicholas moran on 13 Apr 2021
Hello Jan, slightly confused. This is the code path:
  1 Comment
Jan
Jan on 14 Apr 2021
Please post code as text, such that the readers can use it by copy&paste. Screenshots are less useful.
See my analysis in the [EDITED] section of my answer.

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!