Rhinocerotidae
Rhinocerotidae

Reputation: 925

Create N x 2 array from N x 1 array-Matlab

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?

Upvotes: 2

Views: 484

Answers (3)

user44
user44

Reputation: 29

You can try this approach

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

Upvotes: 0

Suever
Suever

Reputation: 65430

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;

Upvotes: 6

Divakar
Divakar

Reputation: 221514

You can also abuse bsxfun for a one-liner -

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

Or matrix-multiplication for that implicit expansion -

A*[0,1]

Upvotes: 8

Related Questions