Can someone explain why the top code works but the bottom one has an error that says "Index exceeds the number of array elements. Index must not exceed 1."

1 vue (au cours des 30 derniers jours)
First Code:
f=@(x) ((2.*x)./((2.*x)-1)).*((2.*x)/((2.*x)+1));
k=1;s=f(1);
for k=2:1000
s=s*f(k);
end
s
s = 1.5704
Second Code:
f=@(x) ((2.*x)./((2.*x)-1)).*((2.*x)/((2.*x)+1));
n=1;p=f(1);
for n=2:1000
p=p*p(n);
end
Index exceeds the number of array elements. Index must not exceed 1.
p
Error code: Index exceeds the number of array elements. Index must not exceed 1.
I am trying to evaluate the following product but only for n=1:1000

Réponse acceptée

Stephen23
Stephen23 le 21 Fév 2025
Modifié(e) : Stephen23 le 21 Fév 2025
"Can someone explain why the top code works but the bottom one has an error that says "Index exceeds the number of array elements. Index must not exceed 1.""
Take a look at the size of p:
f=@(x) ((2.*x)./((2.*x)-1)).*((2.*x)/((2.*x)+1));
p=f(1);
size(p)
ans = 1×2
1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
How many elements does it have? (hint: one)
What do you expect MATLAB to do when ask for the 2nd element of an array that has only one element in it? Because that is exactly what you are doing on the very first loop iteration, when you index into p like this: p(n).
Perhaps on this line
p=p*p(n);
you really intended to write this:
p=p*f(n);
% ^

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Tags

Produits


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by