How to get warning source
19 views (last 30 days)
Show older comments
Good day everyone,
I have a very long matlab code, and I get the folowing warning when runing (about as much as matlab can spill out into the console per second):
Warning: Colon operands must be real scalars. This warning will become an error in a future release.
How do I get the file / line number generating this warning?
Thank you very much.
0 Comments
Accepted Answer
dpb
on 14 Jul 2024
>> x(i:i)
Warning: Colon operands must be real scalars.
Array indices must be positive integers or logical values.
>> [w,wid]=lastwarn
w =
'Colon operands must be real scalars.'
wid =
'MATLAB:colon:operandsNotRealScalar'
>>
The above generated the warning but also errors, but if you've managed to only generate the warning but not an error, then
dbstop if warning
will stop at the first warning; enter the text of the warning ID (wid return variable from lastwarn) to be the specific warning.
dbstop if warning MATLAB:colon:operandsNotRealScalar
9 Comments
Steven Lord
on 16 Jul 2024
The above appears to me to have simply been an oversight or maybe somebody over the years introduced size in place of an initial use of the risky length without including the dim argument. Since it only generated a warning and didn't crash and burn,
FYI, that is planned to change, as the warning message the original poster quoted states. From the Release Notes, "colon now issues a warning when creating vectors if one or more operands are not scalar. For example, expressions like [1 2 3]:2:10 now warn. This warning will become an error in a future release, removing support for nonscalar operands. Previously, colon used the first element of any nonscalar operands to evaluate the expression." [Emphasis added.]
1:size(something) is a common pattern that probably doesn't do what the author intended it to do. Usually either adding the dimension input (if you want to iterate over the rows / columns / pages / etc. of something) or replacing size with numel (if you want to iterate over all the elements using linear indexing) is probably the solution.
dpb
on 16 Jul 2024
Thanks for the reminder of colon behavior with nonscalar elements; I knew that but forgot about it in concentrating on the for construct and thinking about how prevelant the use of length was; it seems to be somewhat less so recently although it is still quite dangerous in that it also may not do what the user expects.
More Answers (1)
Image Analyst
on 15 Jul 2024
Learn to debug your code. Just step through it one line at a time until you see the error appear. See this link
so you can do it yourself and not have to wait for us to figure it out for you.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!