How can I add n columns to a matrix?

조회 수: 44 (최근 30일)
Tom
Tom 2021년 9월 27일
편집: Stephen23 2021년 9월 28일
Dear experts,
I have a Matrix X(4082x2). Now I want to add for example two columns to the matrix with every cell = 0.
That´s how I´ve done it so far:
amount_rows = numel(X(:,1));
randomdata = rand(amount_rows,1);
added_column = 0*randomdata;
X = [X added_column added_column];
Until now, that worked completely fine but my problem is that I now have a dataset where I need to add more than 100 columns. It would be pretty annoying to add those 100 times the added_column into the bracket (I hope you know what I mean). On top of that, I want the script to work for every dataset so that it automatically adds the "added_collumn" e.g. n-times. Somehow like that:
X = [X (added_column)*n]
(in the case described above n =2)
I know that this is not correct but I hope you get the idea.
Thanks in advance.
Kind regards, TG

채택된 답변

Stephen23
Stephen23 2021년 9월 27일
편집: Stephen23 2021년 9월 28일
A simpler, more versatile, and much more efficient approach is to use ZEROS:
R = size(X,1);
C = number_of_new_columns;
X = [X,zeros(R,C)];
Another simple approach is to use indexing (which implicitly fills the other new elements with zeros):
X(1, end+C) = 0 % Thank you Image Analyst
  댓글 수: 2
Image Analyst
Image Analyst 2021년 9월 27일
편집: Image Analyst 2021년 9월 27일
Or, more simply
X(end, end+C) = 0
Steven Lord
Steven Lord 2021년 9월 27일
In the general case where you want to augment a matrix with copies of a vector (not necessarily the zero vector) you can use repmat.
A = magic(3)
A = 3×3
8 1 6 3 5 7 4 9 2
v = [42; -99; NaN]
v = 3×1
42 -99 NaN
B = [A, repmat(v, 1, 5)]
B = 3×8
8 1 6 42 42 42 42 42 3 5 7 -99 -99 -99 -99 -99 4 9 2 NaN NaN NaN NaN NaN
Or if you need to augment with a series of vectors that can be created by arithmetic operations you can use implicit expansion.
c = [1; 2; 3]
c = 3×1
1 2 3
d = 1:5
d = 1×5
1 2 3 4 5
E = [A, v, c+d] % c+d makes a 3-by-5 matrix
E = 3×9
8 1 6 42 2 3 4 5 6 3 5 7 -99 3 4 5 6 7 4 9 2 NaN 4 5 6 7 8

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by