1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
#多准則決策模型-TOPSIS評價方法
##R語言實現-代碼
MCDM
=
function (decision
=
NULL, weights
=
NULL, impacts
=
NULL)
#決策矩陣,權重向量,影響因子
{
if
(missing(weights))
stop(
"缺少'權重向量-weights'"
)
if
(missing(impacts))
stop(
"缺少'影響因子-impacts'"
)
if
(!
is
.matrix(decision) |
is
.data.frame(decision))
stop(
"'決策矩陣-decision'必須是矩陣或數據框"
)
if
(length(weights) !
=
ncol(decision))
stop(
"權重向量長度錯誤"
)
if
(length(impacts) !
=
ncol(decision))
stop(
"影響因子長度錯誤"
)
if
(!
all
(weights >
0
))
stop(
"權重必須大於零"
)
if
(!
is
.character(impacts))
stop(
"影響因子必須是字符型 '+'或'-' 符號"
)
if
(!
all
(impacts
=
=
"+"
| impacts
=
=
"-"
))
stop(
"影響因子只能是字符型 '+'或'-' 符號"
)
weights <
-
weights
/
sum
(weights)
N <
-
matrix(nrow
=
nrow(decision), ncol
=
ncol(decision))
#建一個空矩陣
for
(i
in
1
:nrow(decision)) {
for
(j
in
1
:ncol(decision)) {
N[i, j] <
-
decision[i, j]
/
sqrt(
sum
(decision[, j]^
2
))
}
}
#決策矩陣標准化
W
=
diag(weights)
#建權重對角矩陣
V
=
N
%
*
%
W
#構造加權規范化矩陣
#確定理想方案和負理想方案
u <
-
as.integer(impacts
=
=
"+"
)
*
apply
(V,
2
,
max
)
+
as.integer(impacts
=
=
"-"
)
*
apply
(V,
2
,
min
)
l <
-
as.integer(impacts
=
=
"-"
)
*
apply
(V,
2
,
max
)
+
as.integer(impacts
=
=
"+"
)
*
apply
(V,
2
,
min
)
#構建理想方案和負理想方案距離公式
distance_u
=
function(x) {
sqrt(
sum
((x
-
u)^
2
))
}
distance_l
=
function(x) {
sqrt(
sum
((x
-
l)^
2
))
}
#計算相對接近度並排序
du <
-
apply
(V,
1
, distance_u)
dl <
-
apply
(V,
1
, distance_l)
score <
-
dl
/
(dl
+
du)
outcome <
-
data.frame(
"方案"
=
1
:nrow(decision), 得分
=
score,
排名
=
rank(
-
score))
return
(outcome)
}
Author(s)
Mahmoud Mosalman Yazdi <m.mosalman@gmail.com>
|