Yes, remove the call to intersect, and rely on the results of match to tell you whether there is an overlap. If there are any matches, all(is.na(index)) will be false. Read help for match.
?match -----Original Message----- From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On Behalf Of Hui Du Sent: Wednesday, February 16, 2011 6:29 PM To: r-help@r-project.org Subject: [R] speed up the code Hi All, The following is a snippet of my code. It works fine but it is very slow. Is it possible to speed it up by using different data structure or better solution? For 40000 runs, it takes 8 minutes now. Thanks a lot fun_activation = function(s_k, s_hat, x_k, s_hat_len) { common = intersect(s_k, s_hat); if(length(common) != 0) { index = match(common, s_k); round(sum(x_k[index]) * length(common) / (s_hat_len * length(s_k)), 3); } else { 0; } } fun_x = function(a) { round(runif(length(a), 0, 1), 2); } symbol_len = 50; PHI_set = 1:symbol_len; S = matrix(replicate(M * M, sort(sample(PHI_set, sample(symbol_len, 1)))), M, M); X = matrix(mapply(fun_x, S), M, M); S_hat = c(28, 34, 35) S_hat_len = length(S_hat); S_hat_matrix = matrix(list(S_hat), M, M); system.time( for(I in 1:40000) { A = matrix(mapply(fun_activation, S, S_hat_matrix, X, S_hat_len), M, M); } ) HXD [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. message may contain confidential information. If you are not the designated recipient, please notify the sender immediately, and delete the original and any copies. Any use of the message by you is prohibited. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.