如何组合两个循环

时间:2015-09-14 22:08:29

标签: r

在for()循环教程中遇到了以下练习:

练习4.4。编写一个函数来执行矩阵向量乘法。它应该将矩阵A和向量b作为参数,并返回向量Ab。使用两个循环来执行此操作,而不是%*%或任何矢量化。

假设我使用特定矩阵A(dim:3,4)和矢量b(length(3))。

import java.util.function.*;
class Test {
    public static void main(String... args) {
        check(new Integer(1), o -> o instanceof Integer);
        // Prints "That's it".
        check(new Boolean(true), o -> o instanceof Integer);
        // Prints "That's not it".
    }

    static void check(Object o, Predicate<Object> check) {
        if (check.test(o))
            System.out.println("That's it");
        else
            System.out.println("That's not it");
    }
}

这适用于一个非常具体的情况,即矩阵有3行,长度为3的向量,但还有很多不足之处,我不知道这个练习的好方法是什么,但问题是& #39;使用两个循环&#39;。建议将不胜感激。 THX

1 个答案:

答案 0 :(得分:2)

你正在使用A[i,]*b隐藏内循环,它正在进行矢量化乘法(即隐藏循环)。因此,如果你明确地扩展它,你将有两个必需的循环。

Ab<-function(A,b) {
    if (dim(A)[2] != NROW(b)) stop("wrong dimensions")
    out <- matrix(, nrow(A), 1)
    for(i in 1:dim(A)[1]) {
        s <- 0
        for (j in 1:dim(A)[2]) s <- s + A[i,j] * b[j]
        out[i] <- s
    }
    out
}