How to divide by only the even elements of matrix?

조회 수: 2 (최근 30일)
Daniel Tanner
Daniel Tanner 2020년 5월 5일
답변: KSSV 2020년 5월 5일
Say I have two vectors:
A = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
B = [20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1];
How would I create a third vector that divides the even elements in B by the sequential elements in A. For example, the first element in A (1) divided by the second element in B (19) and then the second element in A (2) divided by the fourth element in B (17). Also if possible, once this has been achieved would it be possibe to cycle through the odd elements, i.e., the eleventh element in A (11) divided by the first element in B (20) then the twelth element in A (12) divided by the third element in B (18).
I tried to have a quick go at writing a for loop for the even elements:
A = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
B = [20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1];
for n = 1:length(B)
C = A(n)/B(n*2);
end
But I wasn't getting anywhere with that.
Any help would be appreciated, thanks!

답변 (1개)

KSSV
KSSV 2020년 5월 5일
A = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
B = [20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1];
% Divide Even
A_even = A(2:2:end) ;
E1 = A_even./B(1:length(A_even)) ;
% Divide Odd
A_odd = A(1:2:end) ;
O1 = A_odd./(B(length(A_even)+1:length(A_odd))) ;

카테고리

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