Digital Signal Processing Reference
In-Depth Information
If missing, a default value of 1 is assumed as the increment in the range-
generating statement (1:7) . Therefore, g(1:7) is equivalent to g(1:1:7).
E.3 Control statem ents
M ATLAB supports several other loop statements ( while , switch , etc.) as
well as the if-else statement. In functionality, these statements are similar to
their counterparts in C but the syntax is slightly different. In the following, we
provide examples for some of the loop and conditional statements by providing
analogy with the C code. Readers who are unfamiliar with C can skip the C
instructions and study the explanatory comments that follow.
Example E.5
Consider the following set of instructions in C:
int X[2][2] = {{ 2, 5 } , { 4,6 }} ;
/* initialize matrix X */
int Y[2][2] = {{ 1, 5 } , { 6,-2 }} ;
/* initialize matrix Y */
int Z[2][2];
/* declare Z */
for (m = 1; m <= 2; m++) {
Z[m][n] = X[m][n] + Y[m][n];
/*Z=X+Y*/
}
Write down the equivalent M ATLAB code for the above instructions. Can the
M ATLAB code be simplified?
Solution
Implementation 1 Following a step-by-step conversion of the C code into
M ATLAB yields
>>X=[25;46]
%Xisinitialized
>>Y=[15;6-2]
%Yisinitialized
>> for m = 1:2,
for n = 1:2,
Z(m,n) = X(m,n)+Y(m,n);
end
end
Implementation 2 The for loops in M ATLAB can be replaced by the while
statement as follows:
>>X=[25;46]
%Xisinitialized
>>Y=[15;6-2]
%Yisinitialized
>>m=1;
>> while (m < 3),
Search WWH ::




Custom Search