How to apply for loop in case of product of function inside double summation?

Hello all, I am trying to code the following double summation that involves product inside it in MATLAB.
----(1)
I had tried the following code :
pr = 0;
for i = 0:1
for j = 0 : 1
pr_1 = a(i)*b(j);
pr = pr+pr_1;
end
end
P = 1-pr;
My query is that is the above code correctly representing equation (1).
Any help in this regard will be highly appreciated.

2 commentaires

That is simply the sum of product of pairs in the given index range for a and b, thus P can be defined like this -
P = 1-sum((a(1:2).')*b(1:2),'all')
Keep in mind that indexing in MATLAB starts from 1.
Though you may not need double for loop as @Dyuman Joshi demonstrated, you can modify your present code as shonn in my answer which i believe is your question about. .

Connectez-vous pour commenter.

Réponses (2)

VBBV
VBBV le 1 Fév 2024
Modifié(e) : VBBV le 1 Fév 2024
R = 0:1;
a = 1:10; b = -10:10;% define values
for i = 1:length(R)
for j = 1:length(R)
pr_1(i,j) = a(i)*b(j);
end
pr(i) = sum(pr_1(i,:));
end
P = 1-sum(pr)
You can modify the existing code as above

5 commentaires

@VBBV, @Dyuman JoshiThank u so much for ur answer.....So could u pls confirm whether code written by me using for loops is correct or not?
Stephen23
Stephen23 le 1 Fév 2024
Modifié(e) : Stephen23 le 1 Fév 2024
"So could u pls confirm whether code written by me using for loops is correct or not?"
It is not correct. Dyuman Joshi already gave you one reason why, and VBBV showed you how to fix it.
@Stephen23, Thank u sir for ur response...Could u pls tell where I am doing wrong in my code...I tried to go through Dyuman Joshi's code but not getting it clearly....
Use
pr_1 = a(i+1)*b(j+1);
instead of
pr_1 = a(i)*b(j);
in your code.
Array indexing in MATLAB starts with 1, not with 0.

Connectez-vous pour commenter.

Matt J
Matt J le 2 Fév 2024
Modifié(e) : Matt J le 2 Fév 2024
The most efficient approach, especially as a and b become longer, is to separate the sums, leading to a one-line computation:
P=1-sum(a)*sum(b);
Even if this is intended to be an exercise in writing loops, it would make more sense to write separate loops for sum(a) and sum(b).

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