2

I have a 1D array (say A) of size N (i.e N x 1; N-rows, 1 Column). Now I want to create an array of size N x 2 (N-rows, 2-columns) with the array A as one column and the other column with a same element (0 in the given example below).

For e.g If

A =[1;2;3;4;5]; 

I'd like to create a matrix B which is

B=[0 1; 0 2; 0 3; 0 4; 0 5]

How do I do this in Matlab?

3 Answers 3

8

You can also abuse bsxfun for a one-liner -

bsxfun(@times,[0,1],A)

Or matrix-multiplication for that implicit expansion -

A*[0,1]
Sign up to request clarification or add additional context in comments.

3 Comments

Love these approaches (+1)
@Divakar: I don't understand in this approach what should I do to get a value other than zero? For e.g a column containing 22 along with A.
@SaravanaKumar You could do bsxfun(@plus,A*[0,1],[22,0]). But for efficiency, I would suggest using @Suever's answer by initializing with B = 22*ones(numel(A), 2); and then B(:,2) = A;. Or just concatenate : B = [22*ones(numel(A),1) A].
6

You can initialize B to be an Nx2 array of all zeros and then assign the second column to the values in A.

A = [1;2;3;4;5];

B = zeros(numel(A), 2);
B(:,2) = A;

%   0   1 
%   0   2     
%   0   3     
%   0   4     
%   0   5  

If you actually just want zeros in that first column, you don't even have to initialize B as MATLAB will automatically fill in the unknown values with 0.

% Make sure B isn't already assigned to something
clear B

% Assign the second column of uninitialized variable B to be equal to A
B(:,2) = A;

Comments

0

You can try this approach

B=[zeros(length(A),1) A]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.