필터 지우기
필터 지우기

Convert vectors with different names to matrix

조회 수: 3 (최근 30일)
salvor
salvor 2017년 11월 2일
편집: Stephen23 2017년 11월 2일
Hi guys,
I have n vectors (1x4000) whose names are a1, a2 up to an. I would like to create a matrix which is the rsult of vertcat(a1,a2,...,an). How can I do it without specifying the names of all the vectors in vertcat?
Thank you!
  댓글 수: 7
salvor
salvor 2017년 11월 2일
편집: salvor 2017년 11월 2일
It means that I have been given a set of 10 different vectors, each of them 1x4000 called a1, a2 up to a10. I want to create a matrix 10x4000 containing these 10 vectors.
Stephen23
Stephen23 2017년 11월 2일
편집: Stephen23 2017년 11월 2일
@salvor: I asked how you are getting this data into your workspace: are you loading the data from a file, or running some function or script, or doing something else?
Data does not just magically appear in a workspace. Some operation has to put it there, like loading from a file. Please tell us how you get that data into your workspace. Then we can help you to write better code.

댓글을 달려면 로그인하십시오.

채택된 답변

OCDER
OCDER 2017년 11월 2일
You could use the workaround of save/load to get what you want.
%Suppose you have these a1, a2 ... an
a1 = rand(1, 4000);
a2 = rand(1, 4000);
a3 = rand(1, 4000);
a13 = ones(1, 4000);
save('TEMPFILE.mat', '-regexp', 'a\d+') %saves variables with names a[number]
a = load('TEMPFILE.mat'); %loads into structure, a.a1, a.a2, a.a3, ...
delete('TEMPFILE.mat'); %delete temp mat file
anums = str2double(strrep(fieldnames(a), 'a', '')); %get the nth number of a
[~, sortidx] = sort(anums); %get the sort order. 1, 10, 2, 3 --> 1, 2, 3, 10
a = struct2cell(a); %convert structure to cell
a = vertcat(a{sortidx}); %sort a in right order, and then combine vertically
  댓글 수: 1
Stephen23
Stephen23 2017년 11월 2일
편집: Stephen23 2017년 11월 2일
Note: sorting into the correct order is simple with my FEX submission natsort.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by