Creatig a matrix from variables in workspace
조회 수: 36 (최근 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!