필터 지우기
필터 지우기

add a column between tow columns

조회 수: 20 (최근 30일)
Hossein
Hossein 2014년 5월 29일
답변: Jos (10584) 2014년 5월 29일
Hi,
I am newbie with matlab. I have a matrix like:
a = [ 2 5 7 ; 3 6 8]
I would like to add new column between column 1 and 2, So I will have:
a = [2 1 5 7; 3 4 6 8]
Let me ask it more general, I want to add a column between any two columns.
Thanks

채택된 답변

Sara
Sara 2014년 5월 29일
Given the array A and the column vector x, let n be the column after which you want to add x into A:
ncol = size(A,2);
cat(2,A(:,1:n),x,A(:,min(n+1,ncol):end))
  댓글 수: 3
Sara
Sara 2014년 5월 29일
As far as I know, you may add x it at the end of A too, so n+1 would be outside A boundaries. It's just a precaution.
Hossein
Hossein 2014년 5월 29일
Clear as crystal now :)

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

추가 답변 (3개)

Hossein
Hossein 2014년 5월 29일
편집: Hossein 2014년 5월 29일
I found answer my self (actually my friend help me with that. but any other solution is still welcomed :) )
x [1;4];
a = [a(:,1) x a(:,2:end)]

Adam
Adam 2014년 5월 29일
If you use it often, some function handling it should not be problem to program.
Adam

Jos (10584)
Jos (10584) 2014년 5월 29일
% DATA
A = [1 2 3 ; 4 5 6] % original matrix
x = [8 ; 9] % values to insert
J = 2 % insert x AFTER column J into A
% ENGINE
B = [A x]
[~,i] = sort([1:size(A,2) J])
B = B(:,i)

카테고리

Help CenterFile Exchange에서 Manual Performance Optimization에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by