Matlab - 用另一个向量替换每一列

时间:2013-10-25 09:22:20

标签: matlab matrix

我的矩阵A有n,n维。 如何用列向量x(大小为n)替换A的每个第二列。

我想在没有任何“for / while”循环的情况下这样做,

有人可以帮帮我吗? 感谢。

2 个答案:

答案 0 :(得分:4)

假设这是您的数据:

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

然后,这就是将向量分配给矩阵的每个第二列的方法:

idx = 2:2:size(A,2)
A(:,idx) = repmat(V,numel(idx))

答案 1 :(得分: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.

如果您希望它从第二列开始,则必须使用floor代替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