FOR LOOP, add value to each row at a time
15 ビュー (過去 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
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
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 Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!