필터 지우기
필터 지우기

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

조회 수: 9 (최근 30일)
David
David 2023년 11월 7일
댓글: Walter Roberson 2023년 11월 7일
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)

채택된 답변

Walter Roberson
Walter Roberson 2023년 11월 7일
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
Walter Roberson
Walter Roberson 2023년 11월 7일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by