how can i dynamically change a file name in dlmwrite?

1 view (last 30 days)
I am trying to make it so that when a file is uploaded the "name2" of my code will change to match the source file that the data was taken from. Code below.The pieces of code that i want to match are bold and italic.
fid = uigetfile('.dat');
[pathstr, name2 ,ext] = fileparts(fid);
S = importfile(fid); name = S.textdata;
x = S.data(:,1); y = S.data(:,2);
n = length(x);
a = ones(n,1); b = (1:n)'; z = zeros(n,1);
m = [a b x y z ; 1 0 0 0 0];
dlmwrite('coords_ name2 .txt',m,' ')

Accepted Answer

Image Analyst
Image Analyst on 6 Nov 2014
See this snippet:
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = 'C:\Program Files\MATLAB';
if ~exist(startingFolder, 'dir')
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
% Now read it in.
% Now create output name
baseOutputFileName = sprintf('Coords_%s', baseFileName);
fullOutputFileName = fullfile(folder, baseOutputFileName);
  2 Comments
Matthew
Matthew on 6 Nov 2014
Thanks, here is what i did to make the file change.
clc clear all close all
fid = uigetfile('.dat');
[pathstr,name2,ext] = fileparts(fid);
S = importfile(fid); name = S.textdata;
x = S.data(:,1); y = S.data(:,2);
n = length(x);
a = ones(n,1); b = (1:n)'; z = zeros(n,1);
m = [a b x y z ; 1 0 0 0 0];
filename = sprintf('coords_%s.txt',name2);
dlmwrite(filename,m,' ')
Image Analyst
Image Analyst on 7 Nov 2014
Any reason why you threw out all the things in there that I used to make it more robust? I mean, why write fragile code when you don't have to?

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!