adding and subtracting elements in the same row in an nested for loop
2 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a question about the use of nested for loops which I cannot found in the several explanations.
My problem is that I have an initial vector with length 10.
t = [5 5 5 5 5 5 5 5 5 5];
I want to add a delta (d) to one and subtract a delta (d) to another value in the same row at the same time, without interfering with the other values.
My assumption is that I have to do this using a nested for loop. So far I am not able to come up with a solution that do not interfere with the other values.
What I want to do is make a new matrix with the different values of t_n in it.
The first nine rows of the matrix are:
t_n(1,:)=[t(1)+d t(2)-d t(3) t(4) t(5) t(6) t(7) t(8) t(9) t(10)];
t_n(2,:)=[t(1)+d t(2) t(3)-d t(4) t(5) t(6) t(7) t(8) t(9) t(10)];
t_n(3,:)=[t(1)+d t(2) t(3) t(4)-d t(5) t(6) t(7) t(8) t(9) t(10)];
t_n(4,:)=[t(1)+d t(2) t(3) t(4) t(5)-d t(6) t(7) t(8) t(9) t(10)];
t_n(5,:)=[t(1)+d t(2) t(3) t(4) t(5) t(6)-d t(7) t(8) t(9) t(10)];
t_n(6,:)=[t(1)+d t(2) t(3) t(4) t(5) t(6) t(7)-d t(8) t(9) t(10)];
t_n(7,:)=[t(1)+d t(2) t(3) t(4) t(5) t(6) t(7) t(8)-d t(9) t(10)];
t_n(8,:)=[t(1)+d t(2) t(3) t(4) t(5) t(6) t(7) t(8) t(9)-d t(10)];
t_n(9,:)=[t(1)+d t(2) t(3) t(4) t(5) t(6) t(7) t(8) t(9) t(10)-d];
Since this is way to complicated and I don't want to write this whole matrix with t(1)-d, t(2)+d etc, I am looking for help. Can anyone tell me how to do this with a loop or any other solution?
0 个评论
采纳的回答
Stephen23
2020-9-16
编辑:Stephen23
2020-9-16
"My assumption is that I have to do this using a nested for loop."
Using array operations would be a much better use of MATLAB, e.g.:
>> d = 3;
>> n = 10;
>> t = repmat(5,1,n)
t =
5 5 5 5 5 5 5 5 5 5
>> m = toeplitz([zeros(1,n-1)],[0,-d,zeros(1,n-2)]);
>> m(:,1) = d;
>> m = m + t % Requires R2016b or later. For earlier versions use BSXFUN.
m =
8 2 5 5 5 5 5 5 5 5
8 5 2 5 5 5 5 5 5 5
8 5 5 2 5 5 5 5 5 5
8 5 5 5 2 5 5 5 5 5
8 5 5 5 5 2 5 5 5 5
8 5 5 5 5 5 2 5 5 5
8 5 5 5 5 5 5 2 5 5
8 5 5 5 5 5 5 5 2 5
8 5 5 5 5 5 5 5 5 2
更多回答(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!