Creatig a matrix from variables in workspace
39 views (last 30 days)
Show older comments
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!
Answers (3)
Massimo Zanetti
on 23 Dec 2016
Edited: Massimo Zanetti
on 23 Dec 2016
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 Comments
Massimo Zanetti
on 27 Dec 2016
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
on 24 Dec 2016
Edited: Stephen23
on 24 Dec 2016
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 Comments
Addy
on 29 Oct 2018
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 Comments
See Also
Categories
Find more on Whos 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!