Replacing multiple columns elegantly with a vector
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Gabriel Seidl
le 1 Fév 2021
Commenté : Gabriel Seidl
le 1 Fév 2021
I am looking for an elegant and simple way to replace a some columns in a matrix (specified by a logical array) with a given column vector, e.g:
M = magic(5);
replace_column = boolean([1 0 0 1 0]); %replace the 1st and 4th column
replace_with = [5;5;5;5;5]; %column vector that the targeted columns should be replaced with
I now want to replace the columns corresponding to the entries of replace_column equal to 1 with the vector specified in replace_with.
I do not want to use a for-loop here, because I think there is a simple solution to this. However, using
M(:,replace_column) = replace_with;
results in an error:
Unable to perform assignment because the size of the left side is 5-by-2 and the size of the right side is 5-by-1.
Do you have an idea how to solve this?
0 commentaires
Réponse acceptée
Fangjun Jiang
le 1 Fév 2021
Modifié(e) : Fangjun Jiang
le 1 Fév 2021
You want to replace two columns but only provided one column of data. Provide the matching data.
M(:,replace_column) =repmat(5,5,2)
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!