# Multiply two terms at a set distance apart from each other in an array

1 vue (au cours des 30 derniers jours)
Tb le 4 Mar 2021
Modifié(e) : Stephen23 le 4 Mar 2021
So, say you have a row vector of 950 values. And you want to find the multiplication between 2 terms 23 elements apart, like 1 and 24, 2 and 25, 3 and 26 etc until 927 and 950. How can this be done?
I have written a for loop but it gives me an error.
Loop:
for i = 1:950
var = array(i+23)*array(i)
end
Error:
Index of array exceeds 950
Any help would be greatly appreciated. Thanks.
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Jan le 4 Mar 2021
Note: "var" is a built-in Matlab function. After shadowing it by using this as name of a variable, you cannot call var() anymore.

Connectez-vous pour commenter.

### Réponses (3)

Stephen23 le 4 Mar 2021
Modifié(e) : Stephen23 le 4 Mar 2021
The MATLAB approach:
v = arr(1:end-23) .* arr(24:end);
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

array = 1:950;
for i = 1:950
disp([ 'i = ' num2str(i) ' : array(' num2str( i+23 ) ')*array(' num2str( i ) ')' ])
var = array(i+23)*array(i)
end
array(951) does not exist.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Jan le 4 Mar 2021
The loop method:
array = rand(1, 950);
for i = 1:950 - 23
v = array(i+23) * array(i)
end
Stephen's vectorized approach is nicer and faster.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by