Different path than current folder

9 次查看(过去 30 天)
Harris
Harris 2012-8-3
My current folder is C:\Users\donald\Documents\MATLAB\RD2\A2\RD
I want to save to C:\Users\donald\Documents\MATLAB\RD2\A2\PE
I use name = strcat('A2','\PE\pe','1','.mat'); then later save with a saving function that i know works.
I get the error "Unable to write file A2\PE\pe1.mat: No such file or directory."
I do not want to change the current folder or use full path names
Thanks!

回答(1 个)

Image Analyst
Image Analyst 2012-8-3
编辑:Image Analyst 2012-8-3
This is so easy. You can do it in one line with strrep(). See full demo:
% This is what you're starting with.
currentFolder = 'C:\Users\donald\Documents\MATLAB\RD2\A2\RD'
% Append a trailing slash so we don't convert RD2 as well as RD.
% Simply change \RD\ to \PE\ using strrep().
% HERE IS THE ONE SINGLE LINE OF CODE YOU WANT:
desiredFolder = strrep(upper([currentFolder '\']), '\RD\', '\PE\')
% If the folder doesn't exist, create it.
if ~exist(desiredFolder, 'dir')
% mkdir(desiredFolder);
end
% Build the full file name with fullfile.
fullFileName = fullfile(desiredFolder, 'pe1.mat')
Alternatively, you can just get the parent folder of RD and then append the folder name you want and the file name:
lastSlashPosition = find(currentFolder == '\', 1, 'last')
parentFolder = currentFolder(1:lastSlashPosition-1)
fullFileName = sprintf('%s/PE/pe1.mat', parentFolder)
% Note: forward slashes work just fine in Windows.

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by