Graphics Programs Reference
In-Depth Information
do very fast operations on the appropriate matrices. matlab's suite of
utility matrices can also come in handy when vectorising code (see help
elmat ).
We now look at a slightly more complicated example. Suppose you
want to generate a matrix a ij with elements:
j
kj
i
a ij =
k = i
0
otherwise
The 5
×
5 version of a is
1 1+2 1+2+3 1+2+3+4 1+2+3+4+5
0 2
2+3
2+3+4
2+3+4+5
0 0
3
3+4
3+4+5
a =
0 0
0
4
4+5
00
0
0
5
13
6
10
15
02
5
9
14
=
00
3
7
12
00
0
4
9
00
0
0
5
A simple loop implementation of this calculation would resemble the
following:
N = 200;
a = zeros(N,N);
for i = 1:N
for j = 1:N
if j>=i
a(i,j) = sum(i:j);
end
end
end
Let us time this code (call it forloop2 ):
>>t0 = clock;forloop2;etime(clock,t0)
ans =
2.9241
There are may different ways that we could vectorise this calculation,
depending on our ingenuity. For now, we note that we can generate the
Search WWH ::




Custom Search