Borrar filtros
Borrar filtros

Why put a semicolon after the last input for an array?

9 visualizaciones (últimos 30 días)
David
David el 7 de Nov. de 2023
Comentada: Walter Roberson el 7 de Nov. de 2023
This is an example from a textbook that I'm working with as a beginner. Why would this have semi colons after the 8.99 and -1.50?
updatePriceTable([19.99, 9.99; 14.99, 8.99;], [-1.00; -1.50;], 1)

Respuesta aceptada

Walter Roberson
Walter Roberson el 7 de Nov. de 2023
Suppose that you are writing out several rows of value using code. You write out the initial [ and you start writing values. You reach the end of the first row. You now have three possible strategies:
  1. Test to see if you are at the last row, and if not then put in ; -- and after you leave the loop, put in the ] and continue with whatever you were doing; OR
  2. write out ; anyhow -- and after you leave the loop, put in the ] and continue on with whatever you were doing; OR
  3. create all of the row-by-row strings in memory, and after you are doing, strjoin() them with ; (which will not put a semi-colon at the end); then put on the ] and write it all out to output, and then continue on
The first strategy requires a last-row test every iteration, which is difficult to vectorize unless you use hacks such as having an output variable that contains semi-colon for all rows except the last but is empty for the last one.
The third strategy requires that the output fits into memory
The second strategy can be vectorized. It's "cost" is that you end up with one extra semi-colon on output that is not strictly needed.
  1 comentario
Walter Roberson
Walter Roberson el 7 de Nov. de 2023
Now imagine that you are typing in numbers from several pages, typing in as many as were on the page and then moving on to the next page. You reach the end of one page, and you have several possible strategies:
  1. You can hold off on putting in the last semi-colon, and flip over the page to see if there are more numbers to put in, and if there are then put in the semi-colon; OR
  2. You can put in the semi-colon on the line, and flip over the page to ssee if there are more numbers to put in, and if not then go back and remove the final semi-colon; OR
  3. you can just put in the potentially unneeded semi-colon and not worry about it. It doesn't hurt to have it there.
Always putting it in is the only efficient way in a situation where it is somehow "expensive" to determine whether there is more data to enter.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by