For Loop operating with last and first entry of array

1 次查看(过去 30 天)
If i have an array like this:
A=[1;5;6;8];
and i apply a simple for loop like this:
for k=1:4
B(k)=A(k)+A(k+1);
end
How can i write the code, so the last entry of my array A makes the operation with the first entry aswell, namely 8+1=9?

回答(1 个)

David Fletcher
David Fletcher 2018-4-4
编辑:David Fletcher 2018-4-4
Like this?
A=[1;5;6;8];
B=A(1:length(A))+[A(2:length(A));A(1)]
B =
6
11
14
9
  2 个评论
Manuel Fuelling
Manuel Fuelling 2018-4-4
My problem is different than the example i gave:
Coeff is a 4x4 Matrix
for m=1:3
syms x y z
eqns = [Coeff(m,1)*x+Coeff(m,2)*y+Coeff(m,3)*z+Coeff(m,4) == 0, Coeff(m+1,1)*x+Coeff(m+1,2)*y+Coeff(m+1,3)*z+Coeff(m+1,4) == 0];
vars = [x y z];
[solX, solY, solZ] = solve(eqns, vars);
arbpt_sym=[solX;solY;solZ];
arbpt_one_point=(double(arbpt_sym)); %mache sie als double
arbpt(:,m) = arbpt_one_point;
end
the last iteration should operate with the last row and first row of Coeff
David Fletcher
David Fletcher 2018-4-4
So you want it to operate as in the previous example but summing successive rows of a 2D matrix (and the last and first row) rather than the columns of the 1D matrix that you presented as your example?
Like this:
A=[1 1 1 1;2 2 2 2;3 3 3 3;4 4 4 4]
B=A(1:size(A),:)+[A(2:size(A),:);A(1,:)]
A =
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
B =
3 3 3 3
5 5 5 5
7 7 7 7
5 5 5 5

请先登录,再进行评论。

类别

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