2013-10-25 41 views

回答

1
%// 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 
+0

前3行用於從X創建矩陣(n,n)? – Rami

+0

@Rami是的。你只需要最後三行。前三個只是創建示例數據 – Dan

+0

爲什麼我需要x向量是矩陣?爲什麼它不能保持簡單的矢量? – Rami

3

假設這是你的數據:

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

那麼這是怎麼了將矢量分配給矩陣的每個第二列:

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

+1這是整潔的 – Dan

相關問題