Fill a nxm matrix with vectorised expression

Hi all,
here my doubt: i have a matrix M with dimensions nxm. The matrix is initially initialised with zeros, and i fill each M(i,j) calling another function:
M = zeros(n,m)
for i = 1:n
for j = 1:m
M(i,j) = another_function(several_inputs);
end
end
is it possible to fill the matrix M without the for loops, but instead using a vectorised expression?
Thanks

4 comentarios

Konstantin
Konstantin el 16 de Oct. de 2020
What is the condition for selecting the function? Is the function different for each cell of the matrix, or is it possible, that the same function will be used for several cells?
KSSV
KSSV el 16 de Oct. de 2020
It depends on what your another_function is.
Andrea Agosti
Andrea Agosti el 16 de Oct. de 2020
Hi, thanks for your aswer. The inputs of the another_function are different for each i,j.
Thanks
Konstantin
Konstantin el 16 de Oct. de 2020
sometimes it works to vectorize the function itself
matrix = another_function(matrix)

Iniciar sesión para comentar.

 Respuesta aceptada

Matt J
Matt J el 16 de Oct. de 2020
Editada: Matt J el 16 de Oct. de 2020

0 votos

No, there is no way to vectorize an element-wise function generically, without considering the specifics of the function. You can avoid for-loop syntax by using arrayfun, but this simply hides the loops from view, it doesn't replace them with something more efficient.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Versión

R2020b

Preguntada:

el 16 de Oct. de 2020

Comentada:

el 16 de Oct. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by