2

I have Matrix A with n,n dimensions. How can I replace every second column of A with column vector x (of size n).

I want to do it without any "for/while" loops,

can someone please help me? thanks.

2 Answers 2

4

Suppose this is your data:

A = rand(11); V = ones(size(A,1),1); 

Then this is how you assign the vector to each second column of the matrix:

idx = 2:2:size(A,2) A(:,idx) = repmat(V,numel(idx)) 
Sign up to request clarification or add additional context in comments.

Comments

2
%// Create example data n = 21 A = magic(n) x = ones(size(A,1),1); %// Replace every second column of A with x starting from the first column m = ceil(size(A, 2)/2); X = x(:, ones(1,m)); %//Replicate x A(:,1:2:end) = X %// Put x in each odd column. 

If you want it to start from the second column then you must use floor instead of ceil

%//Create example data n = 6 A = magic(n) x = ones(n,1); %// Replace every second column of A with x starting from the second column m = floor(size(A, 2)/2); X = x(:, ones(1,m)); A(:,2:2:end) = X 

4 Comments

the first 3 lines are for creating from X a matrix (n,n)?
@Rami yes. You only need the last three lines. The first three are just creating example data
why do I need the x vector to be a matrix? why can't it stay a simple vector?
@Rami Matlab won't allow you to assign a vector to a matrix. You can assign a scalar to every element of a matrix but not a vector. Matrix assignment needs to be 1 to 1, so you you need to change x to a matrix X that has columns equal to the number of columns you are assigning to (and the same rows obviously)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.