Set value to an array element if the index exceeds the number of array elements

Im trying to set the value of an array element to zero if it exceeds the index.
For example let's suppose given the array: A = [1 2 3 4 5]. It has 5 elements. So when I enter A(5), it outputs "5". And when I enter A(6) it outputs an error, which is logic.
My objective is to make a general equation where I calculate with the elements of an array (where the size of the input array is variable) and if some element exceeds the array index, set it to a value (in my case to zero) and continue calculating.
Any suggestion on how to achieve this as simple as possible?
Thanks in advance

 Réponse acceptée

V = 1:5;
k = 6;
try
N = V(k)
catch
V(k) = 0;
end
display(V)
V = 1×6
1 2 3 4 5 0

1 commentaire

Thank you very much for the fast answer. This is exactly what I was looking for.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by