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

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

3 Comments

What do you mean by with another column? which one?
You A(:, n:n:end) looks like the way to go. Without the actual code and variables, we are left to guess. Please tell us the size of A, the value of n, and the size of this "other" column.
Let A be a square matrix (n,n), I want to replace every Nth element. lets say every 4th element.
Ive tried A(:,4:4:n) = v when v is a column vector (n,1) but get a dimensions mismatch
Thanks!

Sign in to comment.

 Accepted 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.

2 Comments

Sorry I wasnt clearer...
I have a column vector v, and I want to replace every Nth column in my matrix with the vector v.
(i am trying to digest all of the answers :) )
that one works. I need to dig in it a little so see why
thank !!!!!

Sign in to comment.

More Answers (1)

indices = n:n:size(A,2);
A(:,indices)=v(:,ones(size(indices)));

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!