gpt4 book ai didi

r - r 中的两个矩阵相减

转载 作者:行者123 更新时间:2023-12-02 16:26:07 24 4
gpt4 key购买 nike

我创建了两个矩阵,如下所示:

    A = c(1,2,3)
B = c(2,4,6)
c = as.matrix(c(3,6,9))

z = as.matrix(cbind(A, B))

现在我想取出矩阵 c 并逐行减去它,例如1-3 = -2 & 2-3 = -1要充分了解 R 编程,我想创建一个 for 循环。请您的所有答案都应该改进我的 for 循环。

 for (i in 1:nrow(z))# for the rows in matrix z
for (j in 1:nrow(c)) # for the rows in matrix c
{
sub = matrix(NA, 3,2) # make a placeholder
sub [i,]= z[i,]-c[j,] # i am not sure whether this right
return((sub))
}

我收到以下错误:

    Error: no function to return from, jumping to top level

我相信我的 for 循环是错误的,任何人都可以帮忙。目的是了解更多有关 R 编程的知识。谢谢

最佳答案

这是一个很好的扫描案例:

sweep(z, 1, c)
# A B
#[1,] -2 -1
#[2,] -4 -2
#[3,] -6 -3

关于r - r 中的两个矩阵相减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35467242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com