how to multiply every element in an array?

o=[3,1,9];
This is an example of array. I want to multiply them each others. For example;
3x1x9 = 27
The lenght of array could be different. How can I calculate the multiplaction with for loop.

 Réponse acceptée

o = [3 1 9];
% no for loop:
p = prod(o);
disp(p);
27
% some for loop:
p = 1;
for ii = 1:numel(o)
p = p*o(ii);
end
disp(p);
27

2 commentaires

Cem Kurukaya
Cem Kurukaya le 12 Avr 2022
thanks a lot
Voss
Voss le 12 Avr 2022
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (1)

Torsten
Torsten le 12 Avr 2022
Modifié(e) : Torsten le 12 Avr 2022
product = prod(o)
is the short version,
product = 1.0;
for i = 1:numel(o)
product = product*o(i);
end
product
is the long version.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by