Matlab - 在没有for语句的情况下将向量减去矩阵的每一行
Matlab - subtract a vector to each row of a matrix without for statement
我有一段考试代码,他们要我做的是为了取得更好的成绩而无需第二个 "for" 语句即可实现同样的事情。
密码是:
piv = 1:n; %// piv: position vector
for k = 1:n-1 %// for each column :
if ((max(abs(A(piv(k:n),k)))) > eps(normA)) %// if pivot is non zero
[~, I] = max(A(piv(k:n),k)); %// find the max index
I = I + (k-1);
piv([k,I]) = piv([I,k]); %// swap pivot elements
A(piv(k+1:n),k) = A(piv(k+1:n),k)/A(piv(k),k); %// calculate the multipliers and save them in the column
for j = k+1:n
A(piv(j),k+1:n) = A(piv(j),k+1:n) - (A(piv(k),k+1:n)*A(piv(j),k)); %// multiply for multipliers and subtract them by the row
end
end
end
这是高斯分解方法,但没关系,问题是我需要得到相同的结果,但 e 和 j 变量没有第二个。
你当然可以杀死最里面的循环bsxfun
. I am leaving it to you to explain to your prof on how it does what it does. Going through the bsxfun docs would be a good idea and in this process you might learn some vectorization techniques
。这是实现 -
parte2 = bsxfun(@times,A(piv(k),k+1:n),A(piv(k+1:n),k))
A(piv(k+1:n),k+1:n) = A(piv(k+1:n),k+1:n) - parte2
我有一段考试代码,他们要我做的是为了取得更好的成绩而无需第二个 "for" 语句即可实现同样的事情。
密码是:
piv = 1:n; %// piv: position vector
for k = 1:n-1 %// for each column :
if ((max(abs(A(piv(k:n),k)))) > eps(normA)) %// if pivot is non zero
[~, I] = max(A(piv(k:n),k)); %// find the max index
I = I + (k-1);
piv([k,I]) = piv([I,k]); %// swap pivot elements
A(piv(k+1:n),k) = A(piv(k+1:n),k)/A(piv(k),k); %// calculate the multipliers and save them in the column
for j = k+1:n
A(piv(j),k+1:n) = A(piv(j),k+1:n) - (A(piv(k),k+1:n)*A(piv(j),k)); %// multiply for multipliers and subtract them by the row
end
end
end
这是高斯分解方法,但没关系,问题是我需要得到相同的结果,但 e 和 j 变量没有第二个。
你当然可以杀死最里面的循环bsxfun
. I am leaving it to you to explain to your prof on how it does what it does. Going through the bsxfun docs would be a good idea and in this process you might learn some vectorization techniques
。这是实现 -
parte2 = bsxfun(@times,A(piv(k),k+1:n),A(piv(k+1:n),k))
A(piv(k+1:n),k+1:n) = A(piv(k+1:n),k+1:n) - parte2