필터 지우기
필터 지우기

convert Vector into matrix ?

조회 수: 7 (최근 30일)
Alex
Alex 2013년 5월 24일
답변: Stephen23 2021년 3월 31일
Hello, i need to convert a vector into matrix like this:
A = [1 2 3 4 5]
into
B=[1 2 3; 2 3 4; 3 4 5]
Any ideas ??

채택된 답변

Youssef  Khmou
Youssef Khmou 2013년 5월 24일
hi Alex
This is not conversion but you are adding new elements to the original vector :
If you have a vector of size Mx1 you can convert it to matrix using function reshape to get a matrix of size PxN such M=P*N.
r=randn(100,1);
y=reshape(r,10,10);
In your case , try :
A=1:5;
t=1;
r=3;
for n=1:3
B(n,:)=t:n+2;
t=t+1;
r=r+1;
end
  댓글 수: 3
Mohammed Ghouse Mohiuddin
Mohammed Ghouse Mohiuddin 2021년 3월 31일
For loops are too complex for me. I hate it. Nobody explains it to me in a logical way.
Image Analyst
Image Analyst 2021년 3월 31일
@Mohammed Ghouse Mohiuddin, uncommented code (like Alex's) can be hard to understand. Everyone should use comments. If you can't figure it out, post a new question with the code you are trying to adapt and an explanation of what you really want to do (if you could adapt it). But read this link first.

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

추가 답변 (6개)

Image Analyst
Image Analyst 2013년 5월 24일
I know it seem really really obvious, but if that is all we have to go on (i.e. no indication that it needs to be generalized in any way), then why not just do this:
B = [A(1:3);A(2:4);A(3:5)]
  댓글 수: 1
Alex
Alex 2013년 5월 24일
i am sorry, my mistake, A is big, it was just an example, exist other way to make this automatic ??

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


Matt Kindig
Matt Kindig 2013년 5월 24일
편집: Matt Kindig 2013년 5월 24일
It might not be very efficient, but I think it should work:
nc = 3; %number of columns in B
nc = nc-1;
c = 1:(length(A)-nc);
B = cell2mat(cellfun(@(n) A(n:(n+nc)), num2cell(c(:)), 'uni', false))

Youssef  Khmou
Youssef Khmou 2013년 5월 25일
hi, there are other alternatives , :
try :
N=32;
A=1:N;
A2=0:N-1;
A2=A2';
B=repmat(A,N,1);
for x=1:N
B(:,x)=B(:,x)+A2;
end

Youssef  Khmou
Youssef Khmou 2013년 5월 25일
hi,
here is the best solution without using loops :
N=32;
A=1:N;
B=repmat(A,N,1);
A2=(0:N-1)';
B2=repmat(A2,1,N);
C=B+B2;

anukriti dureha
anukriti dureha 2013년 5월 25일
hi alex, you can do this:
i=1;
ind=0;
num=3;
while num <=5
ind=ind+1;
z{i}=A(ind:num);
num=num+1;
i=i+1;
end
z=cell2mat(x);b=vec2mat(z,3);

Stephen23
Stephen23 2021년 3월 31일
A = [1,2,3,4,5];
B = hankel(A(1:3),A(3:5))
B = 3×3
1 2 3 2 3 4 3 4 5

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by