FOR LOOP, add value to each row at a time

31 visualizaciones (últimos 30 días)
Nadia Numa
Nadia Numa el 2 de Mzo. de 2021
Comentada: Nadia Numa el 8 de Mzo. de 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 comentario
dpb
dpb el 2 de Mzo. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 2 de Mzo. de 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

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by