function crow_distance = crowding_distance(asset_ratios, F) [m, n] = size(F); for i = 1 : m f = F(i,:); [~, idx] = sortrows(asset_ratios(f,:), f); asset_ratios(f(idx(1))).crowding_distance = Inf; asset_ratios(f(idx(end))).crowding_distance = Inf; for j = 2 : n-1 asset_ratios(f(idx(j))).crowding_distance = ... asset_ratios(f(idx(j))).crowding_distance ... + (asset_ratios(f(idx(j+1))).obj - asset_ratios(f(idx(j-1))).obj)/... (max(asset_ratios(f).obj) - min(asset_ratios(f).obj)); end end这段代码报错:无法将类型为 cell 的值用作索引。 出错 crowding_distance (第 5 行) [~, idx] = sortrows(asset_ratios(f,:), f);如何修改
时间: 2023-11-27 09:53:56 浏览: 62
这个错误是因为 `sortrows` 函数第一个输入参数 `asset_ratios(f,:)` 返回的是一个单元格数组,而不是一个数值数组,无法直接用于索引操作。你需要使用花括号 `{}` 来提取其中的值,例如 `asset_ratios{f,:}`。
下面是修改后的代码:
```
function crow_distance = crowding_distance(asset_ratios, F)
[m, n] = size(F);
for i = 1 : m
f = F(i,:);
[~, idx] = sortrows(asset_ratios{f,:}, f);
asset_ratios{f(idx(1))}.crowding_distance = Inf;
asset_ratios{f(idx(end))}.crowding_distance = Inf;
for j = 2 : n-1
asset_ratios{f(idx(j))}.crowding_distance = ...
asset_ratios{f(idx(j))}.crowding_distance ...
+ (asset_ratios{f(idx(j+1))}.obj - asset_ratios{f(idx(j-1))}.obj)/...
(max([asset_ratios{f,:}].obj) - min([asset_ratios{f,:}].obj));
end
end
end
```
阅读全文