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 commentaires

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!

Connectez-vous pour commenter.

 Réponse acceptée

Wayne King
Wayne King le 23 Nov 2012
Modifié(e) : Wayne King le 23 Nov 2012
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 commentaires

tamirmal
tamirmal le 23 Nov 2012
Modifié(e) : tamirmal le 23 Nov 2012
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 !!!!!

Connectez-vous pour commenter.

Plus de réponses (1)

Matt J
Matt J le 23 Nov 2012
Modifié(e) : Matt J le 23 Nov 2012
indices = n:n:size(A,2);
A(:,indices)=v(:,ones(size(indices)));

Catégories

Produits

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by