Subdividing intervals from unequally spaced numbers
Afficher commentaires plus anciens
Hi,
i want to generate points (say 11, variable xch) for a set of intervals defined by unequal spaced numbers (variable xn_ch). It seems that the code generates the points (xch) but with error, because xch vector dimension should not exceed the dimension of the initial generated numbers (xch, size=5). How to solve? Thanks in advance.
This is the code:
n=5
for i=1:n
xn_ch(i)=cos(pi*(2*i-1)/(2*n+2));
end
for i=1:n
xch=linspace(xn_ch(i),xn_ch(i+1),11)
end
xn_ch
This is the error:
Index exceeds the number of array elements. Index must not exceed 5.
Error in code (line 6)
xch=linspace(xn_ch(i),xn_ch(i+1),11)
Réponses (1)
Manan Jain
le 12 Juil 2023
Hi!
The error you're encountering occurs because the loop index i in the second loop exceeds the range of valid indices for the xn_ch array. In the last iteration of the loop, i becomes 6, while xn_ch has only 5 elements.
n = 5;
for i = 1:n
xn_ch(i) = cos(pi * (2 * i - 1) / (2 * n + 2));
end
for i = 1:n-1
xch = linspace(xn_ch(i), xn_ch(i+1), 11);
end
xn_ch
To solve this issue, you can modify the loop to iterate from 1 to n-1 instead of n.
I hope this helps!
4 commentaires
Angelo
le 12 Juil 2023
n = 5;
xn_ch = cos(pi * (2 * (1:n) - 1) ./ (2 * n + 2))
How to accumulate in a single variable all the points generated from each subinterval?
One way is to put them in a matrix:
npts = 11;
xch = zeros(npts, n-1);
for i = 1:n-1
xch(:,i) = linspace(xn_ch(i), xn_ch(i+1), npts);
end
disp(xch)
Catégories
En savoir plus sur Resizing and Reshaping Matrices 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!