[英]Can someone explain to me the problem with my sum in R
對於給定的矩陣 FI 想要計算其行的 2 范數之和,所以我使用 function sum()
但它不起作用,因為我希望它在這里做一個例子
# The matrix F
> F <- matrix(c(9,1,1,1,4,1),nrow=3)
# index of the sum i
> i=1:NROW(F)
#And here is the result
> sum(norm(F[i,], type = "2")^4)
[1] 7376.60160040254
# and if i calculate each element of the sum i get
> norm(F[1,], type = "2")^4
[1] 6724
> norm(F[2,], type = "2")^4
[1] 289
> norm(F[3,], type = "2")^4
[1] 4
我認為您正在尋找apply
function。它沿矩陣的維度應用 function。
sum(apply(F,MARGIN = 1,function(x){norm(x,type = "2")^4}))
#[1] 7017
您的原因不起作用是因為您將c(1,2,3)
分配給了i
。 然后,當您子集F
時,您只會得到整個矩陣。
i=1:NROW(F)
i
#[1] 1 2 3
norm(F,type="2")^4
#[1] 7376.602
norm(F[1:3,],type="2")^4
#[1] 7376.602
norm(F[i,],type="2")^4
#[1] 7376.602
免責聲明:我沒有評估這種方法的數學有效性,只是以編程方式重新創建了 OP 的期望行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.