How can I write a loop that performs a function to each element in a vector?

5 vues (au cours des 30 derniers jours)
say I have a vector with numbers 234 456 687 643 23 45 and have a function which can only take one value at a time. How would I loop to call the function to each one of the values individually?
  1 commentaire
Ameerh
Ameerh le 4 Oct 2024
Write a program in MATLAB using for loop read all the elements of the vector and print them.

Connectez-vous pour commenter.

Réponse acceptée

Star Strider
Star Strider le 3 Déc 2017
Ideally, you would write your function so that it would allow vectorized operations.
If that is not an option try something like this:
Result = zeros(1:length(vector)); % Preallocate
for k1 = 1:length(vector)
Result(k1) = YourFunction(vector(k1));
end
The length call could be replaced by size (with the appropriate dimension argument), or numel. They all have their appropriate uses, depending on your array.
  7 commentaires
Ameerh
Ameerh le 4 Oct 2024
Write a program in MATLAB using for loop read all the elements of the vector and print them.
Star Strider
Star Strider le 4 Oct 2024
@Ameerh — Do exactly that. If you have problems, post a new Question with your code and describe the problem you are having with it.
I will not do your homeework for you!

Connectez-vous pour commenter.

Plus de réponses (1)

Stephen23
Stephen23 le 3 Déc 2017
Modifié(e) : Stephen23 le 3 Déc 2017
Either use a for loop or arrayfun:
vec = [234,456,687,643,23,45];
arrayfun(@fun,vec)
You might also like to read this:
  3 commentaires
Stephen23
Stephen23 le 3 Déc 2017
@Eden Crespo: your function returns non-scalar output arguments. Simply read the error message and do exactly what it states, that will solve the problem:
arrayfun(@fun,vec,'UniformOutput',false)
Eden Crespo
Eden Crespo le 3 Déc 2017
Sorry I am very new to this. Ill try It thank you!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by