When preallocating, is it possible to declare types?
If so, how can I do it? Is it worthy in terms of efficiency?

 Respuesta aceptada

Stephen23
Stephen23 el 16 de Mayo de 2020
Editada: Stephen23 el 16 de Mayo de 2020

0 votos

"When preallocating, is it possible to declare types? "
When preallocating you can select any suitable data type, e.g.:
A = zeros(2,3, 'uint8')
Read the zeros, ones, nan documentation to know more.
"Is it worthy in terms of efficiency?"
In most cases preallocation is more efficient than not preallocating.

4 comentarios

Thak you very much for your answer. I still have some doubts on this:
  1. Of course, preallocating is usually more efficient that not preallocating. My last question was regarding the type declaration in the zeros function specifically. Can we gain efficiency by declaring the right type beforehand?
  2. If I want to fill a 2-by-3 matrix A with numbers such as 2.2, 2.67, 2.9333..., my guess is that I should write
A = zeros(2,3, 'single')
provided that double is the default type assigned by the function, and that single uses less memory than double.
Are these considerations correct?
Stephen23
Stephen23 el 17 de Mayo de 2020
Editada: Stephen23 el 17 de Mayo de 2020
"Can we gain efficiency by declaring the right type beforehand?"
Before what exactly? What is the next step?
Using single or integer types typically does not improve efficiency of calculations (and in fact can slow calculations down). Storing data with a specific type changes what values can be stored and how much memory the data requires, but is not usually intended to improve/change calculation efficiency.
Fernando Riveiro Formoso
Fernando Riveiro Formoso el 17 de Mayo de 2020
Since preallocating improves efficiency before a for loop that fills a matrix with numbers, I was just wondering whether declaring the type of the numbers we are going to fill the matrix with could also improve efficiency... but seems from your answer it is not the case in general. Thank you very much for your answers!
Walter Roberson
Walter Roberson el 18 de Mayo de 2020
datatype can make a big difference, but which is faster can depend upon the processor. There are a range of processors for which single is always faster than double, but then there can be oddities like double multiplication being faster.
http://nicolas.limare.net/pro/notes/2014/12/12_arit_speed/

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Productos

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by