if the logical expression evaluates to a nonscalar value, all the elements of the argument must be...
TRANSCRIPT
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
1/21
his group of control statements enables you to select at run-time which block of code is executed. To
make this selection based on whether a condition is true or false, use the if statement (which may
include else or elseif). To select from a number of possible options depending on the value of an
expression, use the switch and case statements (which may include otherwise).
You cannot define nested functions within a conditional control block. Nested functions must always be
defined at the top level of a function.if, else, and elseif
if evaluates a logical expression and executes a group of statements based on the value of theexpression. In its simplest form, its syntax is
if logical_expression
statementsend
If the logical expression is true (that is, if it evaluates to logical 1), the MATLAB software executes allthe statements between the if and end lines. It resumes execution at the line following the end
statement. If the condition is false (evaluates to logical 0), MATLAB skips all the statements between
the if and end lines, and resumes execution at the line following the end statement.
For example,
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end
You can nest any number of if statements.
If the logical expression evaluates to a nonscalar value, all the elements of the argument must be
nonzero. For example, assume X is a matrix. Then the statement
if X
statements
end
is equivalent to
if all(X(:))statements
end
The else and elseif statements further conditionalize the if statement:
*
The else statement has no logical condition. The statements associated with it execute if the
preceding if (and possibly elseif condition) evaluates to logical 0 (false).
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
2/21
*
The elseif statement has a logical condition that it evaluates if the preceding if (and possibly elseif
condition) is false. The statements associated with it execute if its logical condition evaluates to logical1 (true). You can have multiple elseif statements within an if block.
if n < 0 % If n negative, display error message.disp('Input must be positive');
elseif rem(n,2) == 0 % If n positive and even, divide by 2.
A = n/2;else
A = (n+1)/2; % If n positive and odd, increment and divide.
end
if Statements and Empty Arrays. An if condition that reduces to an empty array represents a false
condition. That is,
if A
S1
elseS0
end
executes statement S0 when A is an empty array.
switch, case, and otherwise
switch executes certain statements based on the value of a variable or expression. Its basic form is
switch expression (scalar or string)
case value1statements % Executes if expression is value1
case value2
statements % Executes if expression is value2.
.
.
otherwisestatements % Executes if expression does not
% match any case
end
This block consists of
*
The word switch followed by an expression to evaluate.*
Any number of case groups. These groups consist of the word case followed by a possible value for
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
3/21
the expression, all on a single line. Subsequent lines contain the statements to execute for the given
value of the expression. These can be any valid MATLAB statement including another switch block.
Execution of a case group ends when MATLAB encounters the next case statement or the otherwise
statement. Only the first matching case is executed.*
An optional otherwise group. This consists of the word otherwise, followed by the statements toexecute if the expression's value is not handled by any of the preceding case groups. Execution of the
otherwise group ends at the end statement.
*
An end statement.
switch works by comparing the input expression to each case value. For numeric expressions, a casestatement is true if (value==expression). For string expressions, a case statement is true if
strcmp(value,expression).
The code below shows a simple example of the switch statement. It checks the variable input_num for
certain values. If input_num is -1, 0, or 1, the case statements display the value as text. If input_num is
none of these values, execution drops to the otherwise statement and the code displays the text 'othervalue'.
Abram
angga
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
4/21
anggiswitch input_numcase -1disp('negative one');case 0
disp('zero');
case 1
disp('positive one');
otherwisedisp('other value');
end
Note For C programmers, unlike the C language switch construct, the MATLAB switch does not
"fall through." That is, if the first case statement is true, other case statements do not execute.Therefore, break statements are not used.
switch can handle multiple conditions in a single case statement by enclosing the case expression in a
cell array.
switch varcase 1disp('1')
case {2,3,4}
disp('2 or 3 or 4')case 5
disp('5')
otherwisedisp('something else')
end
Back to Top of Page Back to TopLoop Control for, while, continue, break
With loop control statements, you can repeatedly execute a block of code, looping back through theblock while keeping track of each iteration with an incrementing index variable. Use the for statement
to loop a specific number of times. The while statement is more suitable for basing the loop execution
on how long a condition continues to be true or false. The continue and break statements give you morecontrol on exiting the loop.
You cannot define nested functions within a loop control block. Nested functions must always be
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
5/21
defined at the top level of a function.
Note You can often speed up the execution of MATLAB code by replacing for and while loops
with vectorized code. See Techniques for Improving Performance for more information on this.
for
The for loop executes a statement or group of statements a predetermined number of times. Its syntax is
for index = start:increment:endstatements
end
The default increment is 1. You can specify any increment, including a negative one. For positiveindices, execution terminates when the value of the index exceeds the end value; for negative
increments, it terminates when the index is less than the end value.
For example, this loop executes five times.
for n = 2:6x(n) = 2 * x(n - 1);
end
You can nest multiple for loops.
for m = 1:5
for n = 1:100A(m, n) = 1/(m + n - 1);
end
end
Note You can often speed up the execution of MATLAB code by replacing for and while loops
with vectorized code. See Vectorizing Loops for details.
Using Arrays as Indices. The index of a for loop can be an array. For example, consider an m-by-n
array A. The statement
for k = A
statements
end
sets k equal to the vector A(:,i), where i is the iteration number of the loop. For the first loop iteration, k
is equal to A(:,1); for the second, k is equal to A(:,2); and so on until k equals A(:,n). That is, the loopiterates for a number of times equal to the number of columns in A. For each iteration, k is a vector
containing one of the columns of A.
while
The while loop executes a statement or group of statements repeatedly as long as the controlling
expression is true (1). Its syntax is
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
6/21
while expression
statements
end
If the expression evaluates to a matrix, all its elements must be 1 for execution to continue. To reduce a
matrix to a scalar value, use the all and any functions.
For example, this while loop finds the first integer n for which n! (n factorial) is a 100-digit number.
n = 1;
while prod(1:n) < 1e100
n = n + 1;
end
Exit a while loop at any time using the break statement.
while Statements and Empty Arrays. A while condition that reduces to an empty array represents a
false condition. That is,
while A, S1, end
never executes statement S1 when A is an empty array.continue
The continue statement passes control to the next iteration of the for or while loop in which it appears,
skipping any remaining statements in the body of the loop. In for loops, the loop counter is incrementedby the appropriate value (either 1 or the specified step value) at the start of the next iteration.
continue works the same way in nested loops. That is, execution continues at the beginning of the loopin which the continue statement was encountered.
The example below shows a continue loop that counts the lines of code in the file, magic.m, skippingall blank lines and comments. A continue
statement
Abram
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
7/21
angga
anggiis used to advance to the next line in magic.m
without incrementing the count whenever a blank line or comment line is encountered.
fid = fopen('magic.m','r');count = 0;
while ~feof(fid)
line = fgetl(fid);if isempty(line) || strncmp(line,'%',1) || ~ischar(line)
continue
endcount = count + 1;
end
fprintf('%d lines\n',count);
fclose(fid);
break
The break statement terminates the execution of a for loop or while loop. When a break statement is
encountered, execution continues with the next statement outside of the loop. In nested loops, break
exits from the innermost loop only.
The example below shows a while loop that reads the contents of the file fft.m into a MATLAB
character array. A break statement is used to exit the while loop when the first empty line is
encountered. The resulting character array contains the help for the fft program.
fid = fopen('fft.m','r');
s = '';
while ~feof(fid)
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
8/21
line = fgetl(fid);
if isempty(line) || ~ischar(line)
break
ends = sprintf('%s%s\n', s, line);
end
disp(s);
fclose(fid);
Back to Top of Page Back to Top
Error Control try, catch
Error control statements provide a way for you to take certain actions in the event of an error. Use thetry statement to test whether certain commands in your code generates an error. If an error does occur
within the try block, MATLAB immediately jumps to the corresponding catch block. Use the catch part
of the statement to respond in some way to the error.
You cannot define nested functions within a try-catch block. Nested functions must always be defined
at the top level of a function.try and catch
The general form of a try-catch statement sequence is
try
statement
...statement
catch meObj
statement...
statement
end
In this sequence, the statements in the try block (that part of the try-catch that follows the word try
statement, and precedes catch) between try and catch execute just like any other program code. If an
error occurs within the try section The statements between catch and end are then executed. Examinethe contents of the MException object meObj to see the cause of the error. If an error occurs between
catch and end, MATLAB terminates execution unless another try-catch sequence has been established.
Back to Top of Page Back to Top
Program Termination return
Program termination control enables you to exit from your program at some point prior to its normal
termination point.
return
After a MATLAB function runs to completion, it terminates and returns control either to the function
that called it, or to the keyboard. If you need to exit a function prior to the point of normal completion,
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
9/21
you can force an early termination using the return
funAbram
angga
anggiction. return immediately terminates the
current sequence of commands and exits the currently running function.
return is also used to terminate keyboard mode.
Back to Top of Page Back to Top
Was this topic helpful?
Comma-Separated Lists Comma-Separated Lists Dates and Times Dates and
Times
Recommended Products
* MATLAB* Signal Processing Toolbox
* Optimization Toolbox
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
10/21
* Statistics Toolbox
* Control System Toolbox
Get MATLAB trial software
Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB
experts.
Get the Interactive Kit
1984-2010- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy -Preventing Pirac
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
11/21
Abram
angga
anggi
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
12/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
13/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
14/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
15/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
16/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
17/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
18/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
19/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
20/21
-
8/9/2019 If the Logical Expression Evaluates to a Nonscalar Value, All the Elements of the Argument Must Be Nonzero. for Ex
21/21