Creatig a matrix from variables in workspace
37 次查看(过去 30 天)
显示 更早的评论
I have 80 workspace variables of size 1 x 3649. The variables are named t001 t005 t010 t015 t020 t025...etc until t195. I want matlab to read them from workspace and put them all together in a matrix to create a matrix 80 x 3649. Please advise me how to do it.Thnanks!
回答(3 个)
Massimo Zanetti
2016-12-23
编辑:Massimo Zanetti
2016-12-23
How did you get these variables?
It is not good practice to handle workspace variables after their definition. Better saving all these vectors t0xx (at the moment they are created) in a cell array C of size 80-by-1 and then build a matrix with cell2mat(C).
2 个评论
Massimo Zanetti
2016-12-27
Dimitris, avoid using eval.
If you cannot manage to save your variables in a different way (don't save variables with numbered names!!!) such as in a structure or cell, then please consider Stephen Cobeldick answer.
Stephen23
2016-12-24
编辑:Stephen23
2016-12-24
The best solution is to never use numbered variables.
As everyone with experience will tell you, avoid using eval. The trick is to load into a variable (which is a structure):
S = load(C);
Once you have the structure you can identify its fieldnames and do whatever you want with the field data. This will be faster and much less buggy than using evil eval. You would probably do something a bit like this outline (pseudocode):
vec = dir(fullfile(pathname,filestring));
out = ... preallocate a matrix of the right size.
for k = 1:numel(vec)
str = fullfile(pathname,vec(k).name);
tmp = load(str);
fld = fieldnames(tmp);
dat = getfield(tmp,fld{1}); % pick the correct field
out(k,...) = dat;
end
If you have never used the functions in my code then read the documentation for each function carefully, try them out, and you will learn some new functions and how to write better code. That will make it worthwhile!
Also note that you should avoid using cd. Using cd is slow, unnecessary, and makes debugging harder. Just pass the full file path instead, as my code shows.
0 个评论
Addy
2018-10-29
Hi,
I have got the same kind of problem and "Stephen Cobeldick's" answer helped me. "getfield" function did the trick. I had different matrices with each 4 columns with names and I wanted to arrange them in a single matrix to be able to use that as the input vector for ANN.
So this helped me to achieve the result.
I have cleared all the variables except of what I need and saved them in a mat file.
x1=load('featurevector.mat');
x2(:,1)=fieldnames(x1);
feature_vector=[];
for i=1:size(x2,1)
feature_vector=vertcat(feature_vector,getfield(x1,x2{i}));
end
I hope this helps.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!