FOR LOOP, add value to each row at a time
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Nadia Numa
am 2 Mär. 2021
Kommentiert: Nadia Numa
am 8 Mär. 2021
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 Kommentar
dpb
am 2 Mär. 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.
Akzeptierte Antwort
Jan
am 2 Mär. 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!