« Earlier3 items total Later »

Tony's Trick

Here is a technique to replicate a vector of size M-by-1 N times, to create a new matrix of sizeM-by-N. This method is known as Tony's Trick. The first column of the vector is indexed (or referenced) n times:
v = (1:5)' n = 3;

M = v(:,ones(n,1))


gives
M =
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5

Vectorize an operation where elements depend on the previous ones.

n=1000;
x(1)=1;
for j=1:n-1,
   x(j+1) = x(j) + n - j;
end

n=1000;
x(1)=1;
j=1:n-1;
x(j+1) = n - j;
cumsum(x);

Vectorize operations based on column and row indicies

Vectorize this
for i = 1:100
  for j = 1:100
    r(i,j) = sqrt(i^2+j^2);
  end
end


becomes

[i,j]=meshgrid(1:100,1:100);
r = sqrt(i.^2+j.^2);

« Earlier3 items total Later »




Sponsored by

Sole Central

Your one stop shop for Birkenstock and Crocs shoes and sandles.