Translate Matlab Code into R ---- Prim's Algorithm
显示 更早的评论
Hi can someone help me to translate this Matlab code into R Studio Code.
function T = MinST(G)
%%Add comment here describing V1 and V2
V1 = [1];
V2 = 2:length(G);
%%T is the result, set to have no edges
T = zeros(size(G));
%%max is just a big number bigger than any edge weight in G
max = 10;
while (~isempty(V2))
%%* Execution trace: V1, V2, T
%%Add a comment here: what do the following loops do?
min = max;
for i=1:length(V1)
for j=1:length(V2)
if (G(V1(i),V2(j))>0 && G(V1(i),V2(j))<min)
%%add a comment here: what is the condition
%%and what do these lines do?
min = G(V1(i),V2(j));
u = V1(i);
v = V2(j);
end
end
end
%%* Execution trace: u, v, min
%%What does the following line do and do the invaraints
%%of the loops above ensure it is the right thing?
T(u,v) = min;
%%explain the following two lines
V1 = [V1 v];
V2(V2==v)=[];
end
end
5 个评论
Furqan
2014-12-15
编辑:Walter Roberson
about 14 hours 前
per isakson
2014-12-16
krishna
2026-11-20,8:06
explain there working
Walter Roberson
about 14 hours 前
Google AI translates the code to the following:
MinST <- function(G) {
# Add comment here describing V1 and V2
V1 <- c(1)
V2 <- 2:nrow(G)
# T is the result, set to have no edges
T_mat <- matrix(0, nrow = nrow(G), ncol = ncol(G))
# max_val is just a big number bigger than any edge weight in G
max_val <- 10
while (length(V2) > 0) {
#* Execution trace: V1, V2, T_mat
# Add a comment here: what do the following loops do?
min_val <- max_val
for (i in seq_along(V1)) {
for (j in seq_along(V2)) {
if (G[V1[i], V2[j]] > 0 && G[V1[i], V2[j]] < min_val) {
# add a comment here: what is the condition
# and what do these lines do?
min_val <- G[V1[i], V2[j]]
u <- V1[i]
v <- V2[j]
}
}
}
#* Execution trace: u, v, min_val
# What does the following line do and do the invariants
# of the loops above ensure it is the right thing?
T_mat[u, v] <- min_val
# explain the following two lines
V1 <- c(V1, v)
V2 <- V2[V2 != v]
}
return(T_mat)
}
回答(1 个)
Hajar
about 2 hours 前
0 个投票
the function initializes v1 with vertex 1 and v2with all the other vertices . the nested loops examine all edges connecting vertices in v1 to vertices in v2 . the if condition cheks whether its weight is smaller than the current minimum . if so ; min-val is updated and the vertices u and v are stored to identify the edge with the smallest weight .
1 个评论
类别
在 帮助中心 和 File Exchange 中查找有关 Linear Model Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!