如我们想验证:
% 循环的做法
T = zeros(size(X));
for i = 1:size(X, 2),
T = T+X(:, i)*X(:, i)';
end
% 矩阵运算的做法
i = 1:size(X, 2);
X(:, i)*X(:, i)'
x = -5:.001:5;
sigma = 0.75;
y = zeros(size(x));
y = (1-(x/sigma).^2).^2/2;
y(abs(x)>sigma)=0;
plot(x, y)
matlab有强大的布尔索引,python还有强大的list comprehension呢,虽然接下来的python代码并未使用list comprehension,这里只是想说,语言的存在是有其存在的合理性的,大家各有其适定的场所:
import numpy as np
import matplotlib.pyplot as plt
s = .75
x = np.arange(-5, 5, .001)
y = np.where(abs(x) < s, (1-(x/s)**2)**2/2, 0)
plt.plot(x, y, c='r', lw=2)
plt.show()
根据向量创建对角矩阵:
>> diag([1/2 1/3 1/4])
ans =
0.5000 0 0
0 0.3333 0
0 0 0.2500
diag
有多份重载,
function a = sigmoid(z)
a = 1/(1+exp(-z));
end
function a = sigmoid(z)
a = 1./(1+exp(-z));
end
二者唯一的不同正在于,做除法运算时,上边的函数没有点,下边的函数有点,这就导致了,第一个函数不可以接受向量或者矩阵,而第二个函数可以。
f = sum(100*(x(2:end)-x(1:end-1).^2).^2+(1-x(1:end-1)).^2);
patches = zeros(patchSize*patchSize, numPatches);
for i = 1:numPatches,
rnd_patch = images(row_idx(i):row_idx(i)+patchSize-1, col_idx(i):col_idx(i)+patchSize-1, img_idx(i));
patches(:, i) = rnd_patch(:);
end
改造为矢量形式:
patches = reshape(images(row_idx:row_idx+patchSize-1, col_idx:col_idx+patchSize-1, img_idx), patchSize*patchSize, numPatches);