How to use the obtained direction from "dir" to address the "dlmread" & "xlsread" - matlab

I want to read some "xlsx" & "txt" files from directory and process on that. Names of the files are the random word.
so I used a function(getAllFiles) to obtain all directions of those files which I founded in this link: How to get all files under a specific directory in MATLAB?.
when I want to use those direction in dlmread or xlsread it give an error as bellow:
??? Error using ==> dlmread at 55
Filename must be a string.
the code is as follow :
fileList = getAllFiles('/home/Network/econimi/SSS')
A=dlmread(fileList(2));
how can I convert fileList to the string format?

The output of getAllFiles is a cell array. As stated in the manual 'Cell array indices in smooth parentheses refer to sets of cells' which means fileList(2) is a cell as well. To access an element of a cell array, use curvy brackets.
Try:
A=dlmread(fileList{2});

Related

Matlab : Counting image in a folder using matlab GUI

I want to count the number of image in a folder using a GUI created in Matlab guide 2015b.
I have written this code:
Id = 3 (actually the value of id will be given by user at run time)
path =strcat ( ' c:\user\Desktop\New\TrainData\',Id)
path=strcat (path,'\')
d=dir (path)
n=length (d)
It shows the error that dir can not be used for cell input. This code is working when I use command prompt.
It shows error only when I want to use it through GUI. Initially I thought that it's a problem regarding the path.
So I displayed the path but it gave the perfect result.
I am confused. Kindly provide some solutions in Matlab
Instead of strcat you should use fullfile:
path = fullfile('c:\user\Desktop\New\TrainData',num2str(Id))
And be careful with dir, dir also list the subfolder so check that you only take into account the image file:
d = dir(path);
name = d(~[d.isdir]).name
Chances are you're getting your Id variable from a inputdlg or something. It is being read in as a cell array of strings rather than a string. You can check this using iscell:
iscell(Id)
% 1
You don't see any issues until you hit the dir command because strcat is able to handle this just fine but also yields a cell array of strings.
out = strcat('123', {'4'});
class(out)
% cell
If you read your error message thoroughly, the error explicitly states that the input to dir is a cell and not a string. The way to fix this is to first check if Id is a cell array and convert to a string if necessary.
Id = inputdlg('Enter an ID');
% Convert to a string if Id is a cell array
if iscell(Id)
Id = Id{1};
end
% Get a listing of all files/directories
d = dir(fullfile(folder, num2str(I)));
% Get number of files
nFiles = sum(~[d.isdir]);
Also, you don't want to try to concatenate a number with a string (strcat('abc', 1)) because this will convert the number to it's ASCII code. Instead you'll want to use num2str as shown above.

Get a list of all subdirectories in Matlab

I'm trying get an absolute path of all subfolders in project_dirs.
project_dirs='D:\MPhil\Model_Building\Models\TGFB\Vilar2006\SBML_sh_ver\vilar2006_SBSH_test7\Python_project3_IQM_project';
all_project_dirs=dir(project_dirs)
for i=all_project_dirs,
full_dir=fullfile(project_dirs,i.name)
The above code gives a single string of all the subfolder directories concatenated together. How do I modify my code to get a cell array of these absolute paths?
There's a function for that: genpath(). It will give you all directories recursively in a string, split by :. Use strsplit() to parse the result.
You can do this:
all_project_dirs = {all_project_dirs([all_project_dirs.isdir]).name};
How it works:
This selects, among the elements of all_project_dirs, those that are directories;
From them it gets the name field;
The values of that field are contatenated into a cell array.
You may want to remove the first two directory names, which are always '.' and '..':
all_project_dirs = all_project_dirs(3:end);
To obtain full paths, you can use strcat:
all_project_dirs = strcat(project_dirs, filesep, all_project_dirs);
or, as suggested by Jørgen, use fullfile:
all_project_dirs = fullfile(project_dirs, all_project_dirs);

Index out of bounds after reading a text file

I have the following simple code, and I tried to use one of the indices from the .txt file. The index that I want is at (4,1) while the size of my matrix in the .txt file is (8,4). When I run the code, MATLAB give me the following error;
Attempted to access q(4,1); index out of
bounds because size(q)=[1,601]
Can someone help me understand why I receive the error and how to fix it?
Here is the code:
q = fileread('sv11edit.txt');
toe = q(4,1)
The answer will depend on the format of the file sv11edit.txt. However, fileread returns a string of characters. In this case, it gives you a string that is 601 characters long. You receive an error because you assume that q is 8 by 4, but this is not the case.
Check what is being stored in q before you try anything like the second line of your code. The function load may be a better alternative to fileread.

Matlab - Error using save Cannot create '_' because '_____' does not exist

I have some data in a cell array,
data2={[50,1;49,1;26,1];...
[36,2;12,2;37,2;24,2;47.3,2];}
and names in another cell array,
names2={'xxx/01-ab-07c-0fD3/0';'xxx/01-ab-07s-0fD3/6';}
I want to extract a subset of the data,
data2_subset=data2{1,:}(:,1);
then a temporary file name,
tempname2=char(names2(2));
an save the subset to a text file with
save (tempname2, 'data2_subset', '-ASCII');
But I get this error message: _
Error using save
Cannot create '6' because 'xxx/01-ab-07s-0fD3' does not exist.
To try to understand what is happening, I created a mock dataset with simpler names:
names={'12-05';'14-03'};
data={[50,1;29,1;25,1];[35,2;22,2;16,2;38,2];[40,3;32,3;10,3;44,3;43,3];};
data_subset=data{1,:}(:,1);
tempname=char(names(2));
save (tempname, 'data_subset', '-ASCII');
in which case the save command works properly.
Unfortunately I still do not understand what the problem is in the first case. Any suggestions as to what is happening, and of possible solutions?
MATLAB is interpreting the the forward slashes (/) as directory separators and 6 as the intended file name (your second example doesn't have this slash problem).
Since the relative directory tree xxx/01-ab-07s-0fD3/ doesn't exist, MATLAB can't create the file.
To solve the problem, you can either create the directories beforehand using mkdir():
>> pieces = strsplit(tempname2,'/');
>> mkdir(pieces{1:2});
>> save(tempname2, 'data2_subset', '-ASCII');
or replace the / with some other benign symbol like _:
>> tempname3= strrep(tempname2,'/','_');
>> save (tempname3, 'data2_subset', '-ASCII');
(which works for me).

How to randomly select from a list of 47 names that are entered from a data file?

I have managed to input a number data file into a matrix but have been unable to do so for any data that is not a number.
I have a list of 47 names and supposed to generate a random name from the list. I have tried to use the function textscan but was not going anywhere. Also how do I generate a random name from the list? All I have been able to do was generate a random number between 1 to 47.
Appreciate the replies. I should have said I need it in MATLAB sorry.
Here is a sample list of data in my data file
name01
name02
name03
and the code to read it:
fid = fopen('names.dat','rt');
headerChars = fgetl(fid);
data = fscanf(fid,'%f,%f,%f,%f',[4 47]).';
fclose(fid);
The above is what I have to read the data file into a matrix but it is only reading the first line. (Yes it was modified from a previous post here on this forums :/)
Edit: As per the helpful comments from mtrw, and the fixed formatting of the sample data file, I've updated my answer with more detail.
With a single name (i.e. "Bob", "Bob Smith", or "Smith, Bob") on each line of the file, you can use the function TEXTSCAN by specifying '%s' as the format argument (to denote reading a string) and the newline character '\n' as the 'Delimiter' (the character that separates the strings in the file):
fid = fopen('namefile.txt','r');
names = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
Then it's a matter of randomly picking one of the names. You can use the function RANDI to generate a random integer in the range from 1 to the number of names read from the file (found using the NUMEL function):
names = names{1}; %# Get the contents from the cell returned by TEXTSCAN
selectedName = names{randi(numel(names))};
Sounds like you're halfway home. Take that random number and use it as an index for the list.
For example, if you randomly generate the number 23 then fetch the 23rd entry in the list which gives you a random name draw.
Use the RANDOMBETWEEN function to get a random number within your range. Use INDEX to get the actual cell value. For instance:
=INDEX(A1:A47, RANDBETWEEN(1, 47))
The above will work for your specific case of 47 names, assuming they're in column A. In general, you'd want something like:
=INDEX(MyNames, RANDBETWEEN(ROW(MyNames), ROW(MyNames) + ROWS(MyNames) - 1))
This assumes you've named your range of cells "MyNames" (for example, by selecting all the cells in your range and setting a name in the naming box). The above formula works by using the ROW function to return the top row of the MyNames array and the ROWS function to get the total rows in MyNames.