FOR LOOP, add value to each row at a time
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello!
I have a column vector X size (26x1) which has 26 different values. In the FOR loop, I want to add a small value to each row (one at a time) at each step.
For example:
for n=1:1:length(X)
value(n) = 1
X plus = X + value(n)
end
I find that this code adds [value] to every row which is not what I want. It should be:
X plus = [ 1+value,1,1,1,1..]' % at step 1
X plus = [1, 1+value,1,1,1,...]' % step 2
X plus = [1,1,1+value,1,1...]' % step 3
and so on...
It should maintain the original values and only add value to the corresponding row as determined by n. Any help is appreciated, thanks!
1 commentaire
dpb
le 2 Mar 2021
MATLAB addresses variables not subscripted as the entire array; if you want to only address a portion of an array, you must use the desired subscript for the element(s) wanted.
In this case that would be
Xplus(n)=...
Also as written "X plus" is not a valid variable name; no embedded spaces are allowed and you should also preallocate arrays.
Réponse acceptée
Jan
le 2 Mar 2021
X = ones(1, 10);
for n = 1:size(X, 2)
Y = X; % Copy original value
Y(n) = Y(n) + 1;
... do what you want to do with Y
end
Or:
X = ones(1, 10);
for n = 1:size(X, 2)
Xback = X(n);
X(n) = X(n) + 1;
... do what you want to do with X
X(n) = Xback; % Restore original value
end
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!