give the matrix a name
15 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
Azzi Abdelmalek
2013-8-2
编辑:Azzi Abdelmalek
2013-8-2
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 个评论
Azzi Abdelmalek
2013-8-3
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
2013-8-3
编辑:Cedric
2013-8-3
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}.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!