FOR LOOP, add value to each row at a time

5 次查看(过去 30 天)
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 个评论
dpb
dpb 2021-3-2
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.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2021-3-2
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by