This will fix it:
D = 'D:\2nd year\C0001.tifroiSTR1';
S = dir(fullfile(D,'*.jpg'));
for k = 1:numel(S);
[~,name,ext] = fileparts(S(k).name);
filename = fullfile(D,[name,'.dat']);
end
The problem with your code starts on this line:
[filepath, basename, ext] = fileparts(filename);
because filename does not contain the path information at all (only the name of the file), then filepath will be empty and totally pointless. So when you construct the filepath again using fullfile using filepath there is no path... and MATLAB looks in the current directory (which is what you are telling MATLAB to do when there is no path). I fixed this by providing the path D to fullfile, just like you did with dir yourself.
The problem is a more general one though: beginners prefer to rely on what they imagine their computer is doing, or what they wish their computer is doing. But code does not care what is in your head, nor what you want it to do. It will do what it is written to do. And your job, if you want to learn how to write good code, is to look at what the code is doing: if you had looked at your variables (which is a very basic step in bugfixing) then you would have found your path information was missing.
Best Answer