How to divide by only the even elements of matrix?

2 visualizaciones (últimos 30 días)
Daniel Tanner
Daniel Tanner el 5 de Mayo de 2020
Respondida: KSSV el 5 de Mayo de 2020
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!

Respuestas (1)

KSSV
KSSV el 5 de Mayo de 2020
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))) ;

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by