Stuart’s MATLAB Videos

Watch and Learn

Understand If statement behavior on vectors 2

Posted by Doug Hull,

In teaching new MATLAB users, I often see them accidentally use a vector as an input to an if statement. This is not likely what they intend and it is often an overlooked syntax error. In this video, I show the error as it is often coded and a simple example showing the outcomes of different vectors.

2 CommentsOldest to Newest

Oliver Woodford replied on : 1 of 2
The result of the following code would suggest it isn't quite as simple as an if doing an implicit all: if [], disp('[]'); end; if all([]), disp('all([])'); end;
Dennis Jaheruddin replied on : 2 of 2
I believe it should in fact not only be an all, but also an any. As such: v = []; if any(v)&&all(v) 'Yes' else 'No' end