putting some matrix in a cell arrays
Show older comments
There are some Matrix, it's needed putting each of them in an array of a cell that the name of that array be equaled with the name of related matrix.
for example:
a=[1 2 3 4 5 3 2]; b=[4 3 5 67 8 8 7]; c=[3 3 2 4 65 7 8 89];
CELL{1,1}=a; CELL{1,2}=b; CELL{1,3}=c;
Now Question is: how could also be put names of above matrix in CELL?
Accepted Answer
More Answers (1)
Walter Roberson
on 24 Sep 2011
In theory the below should work:
var2name = @(varargin) arrayfun(@inputname, 1:nargin, 'Uniform',0);
Then
CELL = var2name(a,b,c);
13 Comments
mohammad
on 24 Sep 2011
mohammad
on 24 Sep 2011
mohammad
on 24 Sep 2011
Walter Roberson
on 24 Sep 2011
Sorry, you question is confusing.
I suspect the answer is:
var2cell = @(varargin) [varargin; arrayfun(@inputname, 1:nargin, 'Uniform',0)];
Unfortunately my access to my MATLAB server is down this afternoon, so I cannot test this.
If it works, CELL{1,K} would be the variable value, and CELL{2,K} would be the variable name.
mohammad
on 24 Sep 2011
mohammad
on 25 Sep 2011
Walter Roberson
on 25 Sep 2011
Looks kind of useless to me. The name recorded would just be 'r' in each case.
The var2cell code was designed for the case where "the name of the array" is the variable name it is stored in.
And you have used cell as a variable name, destroying its meaning as an important call.
cd(myfolder);
d=dir('*.xls');
numfile = length(d);
CELL = cell(2,numfile);
for i = 1:numfile
f=d(i).name;
r=xlsread(f);
CELL{1,i} = r;
CELL{2,i} = f;
end
mohammad
on 25 Sep 2011
Fangjun Jiang
on 25 Sep 2011
@mohammad, it seems to me that you went a long route to solve the problem. My understanding is that you have 600 Excel files, you want to read the data for each file and assign the data to a variable that has the same name as the Excel file, and you want to have this name in a string. Use the dynamic field name of a structure can achieve this.
For example, if you have file MyData.xls, you will be able to get
Files=dir('*.xls');
FileName=Files(1).name; %FileName will be 'MyData.xls'
VarName=strrep(FileName,'.xls','');
Str.(VarName)=xlsread(FileName); %or use COM server
Then, you'll have Str.MyData containing the data from MyData.xls, Str.OtherData from OtherData.xls, etc.
Is that what you want?
mohammad
on 25 Sep 2011
Walter Roberson
on 25 Sep 2011
It would be a good idea to instead use
VarName = genvarname(strrep(FileName,'.xls',''));
in case the file name started with a number or had a character which is not allowed for MATLAB variable names.
Fangjun Jiang
on 25 Sep 2011
Agree! That's a good programming practice. +1
mohammad
on 26 Sep 2011
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!