필터 지우기
필터 지우기

Inserting a column in a matrix without deleting any column

조회 수: 298 (최근 30일)
joseph Frank
joseph Frank 2011년 2월 9일
댓글: Praanesh Sambath 2020년 3월 8일
Hi,
I am wondering of there is a function that enables me to insert a column in a matrix (similar to insert column in excel) without replacing any existing column. For example I have Matrix "A" which is 4x4 and I want to insert a vector "B" after the second column of "A" in order to obtain "A" 4x5 where the 3rd column of "A" is vector "B"

채택된 답변

Martijn
Martijn 2011년 2월 9일
Suppose you have:
>> A=reshape(1:16,4,4)
A =
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
>> B=(17:20)'
B =
17
18
19
20
Then you could obtain the desired matrix C by:
>> C = [A(:,1:2) B A(:,3:4)]
C =
1 5 17 9 13
2 6 18 10 14
3 7 19 11 15
4 8 20 12 16
So you take the first two columns of A concatenate the column B and then concatenate the last two columns of A.
You can generalize this a bit into:
>> D = [A(:,1:N) B A(:,N+1:end)]
Where N then stands for "insert B after the Nth column".
  댓글 수: 3
Rene M
Rene M 2020년 2월 26일
How do I do this in a cell array?
Praanesh Sambath
Praanesh Sambath 2020년 3월 8일
how do I do this if I want B to be in between all the clumns of A

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

추가 답변 (1개)

Izi
Izi 2012년 12월 19일
What about inserting a column which dimensions are not consistent?
  댓글 수: 1
Sarah
Sarah 2016년 9월 1일
In MATLAB, a matrix must have internally consistent dimensions. To insert a column like in the example above, you would have to make sure (one way or another) that it had the same number of rows as the rest of the matrix. You would either have to pad it by adding zeros, NaNs, or some distinct number (e.g., -99999) to make up the length if it was too short, or you'd have to effectively pad the matrix if the column was too long.
I suppose you could also create a column of the appropriate length and interpolate so that the resolution of your new column matched that of the matrix-- there's a function in the Image Processing toolbox (imresize) that lets you specify the size you'd like a 2D matrix to be and appropriately re-grids some input dataset. I can't think of why this wouldn't work for a single column vector.

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by