MATLAB: What is the elegent way to replace every Nth column in a matrix with another column

beginnerMATLAB

It looks easy with a for loop, but I am a beginner and was told to try and avoid for loops…
I though abot something that looks like A(;,n:n:end) but I get a "dimensions mismatch error"
Thank you

Best Answer

B = randn(10,10);
% replace every 3rd column with x
x = randn(10,1);
N = 3;
indices = 1:N:size(B,2);
x = repmat(x,1,length(indices));
B(:,indices) = x;
Probably you are trying to replace a matrix which you get with A(:,1:n:end) with a vector. The sizes have to match.