Filter löschen
Filter löschen

give the matrix a name

37 Ansichten (letzte 30 Tage)
Nicolas
Nicolas am 2 Aug. 2013
Beantwortet: Bhavani A am 23 Jun. 2021
Hi,
I import some text files, and i extracting just the number from each text file and I want to save the matrix with the shorten name of that text file to differentiate each of them).
But i have a problem with this line : Name{1} = [dataArray{1:end-1}]; I don't know how to say "create a matrix called the name inside Name{1} and which contains dataArray{1:end-1}"
I think it is due to the size of Name(1) and the size of dataArray{1:end-1}, but i can't figure it out.
Thank you
clear all
list_files2load = dir('*.txt');
files = {list_files2load.name};
m = length(files);
for i = 1 : m
delimiter = ' ';
startRow = 9;
endRow = 198;
fileID = fopen(files{i},'r');
dataArray = textscan(fileID, formatSpec, endRow-startRow+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'HeaderLines', startRow-1, 'ReturnOnError', false);
fclose(fileID);
Name = regexprep(files{i}(1:length(files{i})-4),'[^\w'']','');
Name(1) = [dataArray{1:end-1}];
clearvars filename delimiter startRow endRow formatSpec fileID dataArray ans;
end

Antworten (2)

Azzi Abdelmalek
Azzi Abdelmalek am 2 Aug. 2013
Bearbeitet: Azzi Abdelmalek am 2 Aug. 2013
Why do you want to create a name for each matrix, put them all in one cell array
Example
M{1}=[1 2;3 4]
M{2}=[5 6;7 8]
Why you have to avoid creating names? Look at
  3 Kommentare
Azzi Abdelmalek
Azzi Abdelmalek am 3 Aug. 2013
You can differentiate them by their indices:
M{1} is the first one and so on, you can also associate to each matrix a name
Example
M{1,1}=[1 2;3 4] % your matrix
M{1,2}='matrix1'
M{2,1}=[4 4;5 6] % your matrix
M{2,2}='matrix2'
Now , If you insist you can use Eval function, which is strongly not recommended
eval('matrix1=[1 2;3 4]')
Cedric
Cedric am 3 Aug. 2013
Bearbeitet: Cedric am 3 Aug. 2013
It is almost never a good idea to create dynamic variable names. As Azzi is explaining, it is much better to have a cell array of matrices, that you build so a matrix corresponding to a given file name has the same index in the array of matrices as the file name in the cell array of file names.
You already have a cell array of file names, files, so the only thing that is left is to prealloc a cell array of matrices before the FOR loop, e.g.
data = cell(size(files)) ;
and then, within the FOR loop, you store whatever you read as
data{i} = ...
With this, data{5} for example is the matrix corresponding to files{5}.

Melden Sie sich an, um zu kommentieren.


Bhavani A
Bhavani A am 23 Jun. 2021
medals_2(2,:) = 9 == Rev_medals_2;
I am getting this output as error

Kategorien

Mehr zu Filename Construction finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by