Getting a type error when attempting to move a file - matlab

I'm trying to move a file into a folder with this code
function addImage_Callback(hObject, eventdata, handles)
% get the file to add to another folder
[baseName, folder] = uigetfile();
% get the full file path of the file to add
fullFilePath = fullfile(folder, baseName);
% get the full folder path of the folder currently selected in the listbox
selectedFolder = get(handles.folders,'string');
selectedFolder = selectedFolder{get(handles.folders,'value')};
% move the file to the folder
moveFile(fullFilePath, selectedFolder);
And receiving this error
Undefined function 'moveFile' for input arguments of type 'char'.
Error in niceinterface>addImage_Callback (line 549)
moveFile(fullFilePath, selectedFolder);
Does anyone know what's going on? The matlab spec for movefile says that it takes strings and the code that I've used to get the folders/files has worked previously.
After 'disp'ing them I received the following output
D:\Downloads\44d9de8db7c840bf0f3fabc9371f9e0d.jpeg
D:\ImageViewer
Thanks all!

Related

Creating a valid filename with dir and fullfile

I keep running across this error in my code:
Path = 'C:\Users\18606\OneDrive\Documents\Spheroids For Brandon\Spheroids\1-8WT';
Content = dir(Path);
SubFold = Content([Content.isdir]); % Keep only the directories
MyData = [];
for k = 3:length(SubFold)
F = fullfile(Path, SubFold(k).name);
fileID = fopen(F);
MyData{end+1} = fopen(fileID,'%s\n');
fclose(fileID);
Resulting in the error:
Error using fopen
Invalid filename (line 8)
The code is trying to iterate over multiple images in multiple subfolders of the main. The goal is to process the images with an edge detection algorithm for each file, but that's besides the point. Why would the program give an invalid file name when the path, content and subfolders are all specified in the code? Do the variables mentioned have anything to do with the error? Finally, is there a better way to open and read the images iteratively?
Reading in files sequentially is indeed usually done through looping over a dir() call, i.e. your strategy is valid. What's going wrong here, is that Path is a path to a directory, not a file. SubFold then are only directories as they are found on the Path. fullfile(Path, SubFold(k).name) finally creates a path to a subdirectory of Path. A subdirectory is not a file, thus fopen will tell you that it's an incorrect filename.
You'll probably need another dir() call, e.g. dir(F) to get all files on the path specified by F.

MATLAB: Invalid file identifier despite of permissions

I am having the following code:
%% Methods
function obj = loadDataGroundTruth(obj)
dataFile = [obj.Configuration.dir.datafiles,'.csv'] ;
% Open the data file
fid = fopen(dataFile,'r+'); %# open csv file for reading
% Scan data file until get to the segments part
bIdFound = false ;
while ((~feof(fid)) & (~bIdFound))
line = fgets(fid); %# read line by line
stringId = sscanf(line,'%s'); %# sscanf can read only numeric data :(
% Stop when we reach the trajectories section
if strcmp(stringId, 'Segments')
bIdFound = true ;
end
end
% Exit if there is not trajectories section in the file
if (~bIdFound)
% Close file descriptor
fclose(fid);
error('This data file does not contain motion information') ;
end
which is supposed to lead the .csv files and do some work with them. However, I get the error specified in the title. Full trace can be seen below:
Error using feof
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in vicon.DataLoaderVICON/loadDataGroundTruth (line 99)
while ((~feof(fid)) & (~bIdFound))
Error in vicon.DataLoaderVICON (line 82)
obj.loadDataGroundTruth() ;
Error in vicon.DataLoaderVICONEdges (line 39)
obj = obj#vicon.DataLoaderVICON(varargin{:})
Error in sequence.SequenceVICON (line 51)
obj.DataLoader = vicon.DataLoaderVICONEdges(directory,...
Error in Lshape0001 (line 21)
seq = sequence.SequenceVICON(SEQUENCE_NAME,...
The problem I suspect though is in this line:
while ((~feof(fid)) & (~bIdFound))
Before anyone tells me to do so: I've already launched Matlab 2017b with sudo rights (Ubuntu 16.04) and I've added the entire folder to the path (with its subfolders).
Thanks in advance.
Okay, figured out, thanks to contributions of user obchardon.
I've noticed that the path had somehow ./ included in it as well, which shouldn't have been the case. The file I was trying to run probably was written in a Windows machine, and thus had different symbols/notation in the path. Once I printed the path it was trying to load the file from, I've noticed that it should not have ./. I removed that from the path and it worked.

Shortcut for saving file in current directory with correct name?

Is there any shortcut for saving an open file into the current directory with the current name? If I download multiple files with the same name they go into my Downloads folder and they end up with names like function (1).m instead of function.m.
At this point it's easy to open the file and see the contents by opening the file from my web browser- MATLAB sees the file extension and opens it. However, if it's a function, I have to Save As and move/rename the file before I'm able to use the code.
Edit: Since MATLAB insists that the file name be the same as the function name I'm hoping that there's a shortcut that saves an open file directly to the current MATLAB path and names it appropriately.
Since MATLAB convention is that the file name is the same as the function name I'm hoping that there's a shortcut that saves an open file directly to the current MATLAB path and names it according to the function name specified in the file.
You will need a directory which is always on the Matlab path. This can be achieved by adding one in the startup.m script.
Then you should save the below function savefunc.m to that directory, so you can always call it.
function savefunc(FuncName, Directory)
% Set directory if not given, default is working directory
if nargin < 2; Directory = pwd; end
% Get active document
ActiveDoc = matlab.desktop.editor.getActive;
% Set FuncName if not given, or if FuncName was empty string
if nargin < 1 || strcmp(FuncName, '');
% Get function name
FuncName = ActiveDoc.Text; % Entire text of document
% Could use indexing to only take first n characters,
% and not load entire string of long function into variable.
% FuncName = ActiveDoc.Text(1:min(numel(ActiveDoc.Text), n));
FuncName = strsplit(FuncName, '('); % Split on parenthesis
FuncName = FuncName{1}; % First item is "function [a,b,c] = myFunc"
FuncName = strsplit(FuncName, ' '); % Split on space (functions don't always have equals)
FuncName = strtrim(FuncName{end}); % Last item (without whitespace) is "myFunc"
end
% Save the file
saveAs(ActiveDoc, fullfile(Directory, [FuncName, '.m']));
end
Now, say you have just created the following Untitled.m:
function [a,b,c] = mytest()
a = 1; b = 1; c = 1;
end
The shortcut: just have Untitled.m open, and type into the Command Window
savefunc()
Untitled.m will be saved as mytest.m in the current working directory. Notice you can also pass a different function name and save-as directory if you wish, making this useful for other occasions.
You can pass an empty string as the FuncName if you want to specify the directory but use the auto-naming.
You could extend this using matlab.desktop.editor.getAll to get all open documents, then loop through them for saving.
For more info, type help matlab.desktop.editor in the Command Window, online documentation seems lacking.
matlab.desktop.editor: Programmatically access the MATLAB Editor to open, change, save, or close
documents.
Finally, note there is no need for a "Save successful" type message, since you will see the file name change, and also receive an error if it fails (from the saveAs docs):
If any error occurs during the saveAs operation, MATLAB throws a MATLAB:Editor:Document:SaveAsFailed exception. If the operation returns without an exception being thrown, assume that the operation succeeded.

read image permission in Matlab

I'm trying to access images in a matlab interface
my code is as follows:
global im2 im
axes(handles.axes4);
[path1, user_cance]= imgetfile();
if user_cance
msgbox(sprintf('Error'), 'Error', 'Error');
return
end
srcFiles = dir('C:\Users\User\Desktop\images test\yale faces\yalefaces\..');
% yale faces is the database folder
for i = 1 : length(srcFiles)
file_name=dir(strcat('C:\Users\User\Desktop\images test\yale faces\yalefaces'));
im2=imread(strcat('C:\Users\User\Desktop\images test\yale faces\yalefaces',file_name(i).name));
%processing of read image
end
the issue is that when I run the code, it gives the following error:
Can't open file "C:\Users\User\Desktop\images test\yale faces\yalefaces" for
reading;
you may not have read permission.
Does anyone know how to solve this issue?
When you do a directory listing (without any wildcards) you are going to get the current directory '.' and parent directory as well '..'. You can't read these like files because they are directories. You will need to filter out the directories prior to trying to read them with imread.
files = dir('C:\Users\User\Desktop\images test\yale faces\yalefaces');
% Remove directories
files = files(~[files.isdir]);
As a side note, it is very hard to tell what your code is doing, but I'm pretty sure it doesn't do what you hope.
It seems like you want to get all images within the database. If that's so, you'll want to do something like.
folder = 'C:\Users\User\Desktop\images test\yale faces\yalefaces';
% Get a list of all files in this folder
files = dir(folder);
files = files(~[files.isdir]);
for k = 1:numel(files)
% Append the folder with the filename to get the path and load
im2 = imread(fullfile(folder, files(k).name));
end
I highly discourage using strcat to construct file paths particularly because it removes trailing/leading whitespace from each input which can corrupt a filename. fullfile was designed for exactly this so please use that.

Launch a Matlab script based on a file extension

Hi I'm trying to create a matlab script in a way that it reads all files in a directory and launches a different command for every file extension.
I have:
teqc1.azi
teqc1.ele
teqc1.sn1
teqc2.azi
teqc****
what i need is that script reads the files and launches recursively the command:
`teqc1.azi -> plot_compact_2(teqc1.azi)`
`teqc1.ele -> plot_compact_2(teqc1.ele)`
`teqc1.sn1 -> plot_compact_2(teqc1.sn1)`
`teqc**** -> plot_compact_2(teqc****)`
This is what I've come up to right now:
function plot_teqc
d=dir('*'); % <- retrieve all names: file(s) and folder(s)
d=d(~[d.isdir]); % <- keep file name(s), only
d={d.name}.'; % <- file name(s)
nf=name(d);
for i=1:nf
plot_compact_2(d,'gps');
% type(d{i});
end
Thanks
Then you'll need the dir function to list the folder contents and the fileparts function to get the extensions.
You can also have a look at this question to see how to get a list of all files in a directory that match a certain mask.
So:
% get folder contents
filelist = dir('/path/to/directory');
% keep only files, subdirectories will be removed
filelist = {filelist([filelist.isdir] == 0).name};
% loop through files
for i=1:numel(filelist)
% call your function, give the full file path as parameter
plot_compact_2(fullfile('/path/to/directory', filelist{i}));
end