如何将MatLab代码中的数据修改为csv文件

问题描述 投票:0回答:1

我有下面这张图。graph I created in code

当前,它可以在MatLab代码中使用以下数据来工作:

 function [] =  TestKShortestPath(case_number)
switch case_number
    case 1
        netCostMatrix = [inf 1 inf 1 ; 1 inf 1 1 ;inf 1 inf inf ;inf inf inf inf ];
        source=3;
        destination=4;
        k = 5; 
            otherwise
        error('The only case options available are 1');
end

我的问题是,我想更改要输入文件(.csv)的数据,这样做如何修改上述代码(尤其是第4行)?这里有我的数据文件(在.csv中,行表示边,第1列和第2列表示节点,第3列表示成本与上述数据相同,情况1):

1,2,1
2,1,1
2,4,1
1,4,1
2,3,1
3,2,1

非常感谢

matlab matrix graph file-io shortest-path
1个回答
0
投票

以下内容将使您启动并运行:

% load the data from the csv file
data = readmatrix('your-data.csv');
% highest number node in graph
N = max(max(data(:,1:2)));
netCostMatrix = inf * ones(N, N);
% convert the node indices to cost matrix indices and set the cost values
netCostMatrix(sub2ind(size(m), data(:,1), data(:,2))) = data(:,3)

结果:

netCostMatrix =

   Inf     1   Inf     1
     1   Inf     1     1
   Inf     1   Inf   Inf
   Inf   Inf   Inf   Inf
© www.soinside.com 2019 - 2024. All rights reserved.