adding and subtracting elements in the same row in an nested for loop

조회 수: 1 (최근 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?

채택된 답변

Stephen23
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
  댓글 수: 1
Chris Ron de
Chris Ron de 2020년 9월 16일
Thanks a lot. Did not realise that this kind of matrix was called toeplitz and that it can solve my problem.
Is it also possible to change the first column with the other columns with this kind of array operation or do I have to make some other versions of m in which I will switch columns?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by