如何将MatLab代码中的数据修改为csv文件
How to modify data in MatLab code to be csv file
我有下面这张图。
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
非常感谢
以下应该让你起来 运行:
% load the data from the csv file (matlab 2019a+)
data = readmatrix('your-data.csv');
% or older versions of matlab
data_table = readtable('your-data.csv');
data = data_table.Variables;
% 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(netCostMatrix), data(:,1), data(:,2))) = data(:,3)
结果:
netCostMatrix =
Inf 1 Inf 1
1 Inf 1 1
Inf 1 Inf Inf
Inf Inf Inf Inf
我有下面这张图。 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
非常感谢
以下应该让你起来 运行:
% load the data from the csv file (matlab 2019a+)
data = readmatrix('your-data.csv');
% or older versions of matlab
data_table = readtable('your-data.csv');
data = data_table.Variables;
% 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(netCostMatrix), data(:,1), data(:,2))) = data(:,3)
结果:
netCostMatrix =
Inf 1 Inf 1
1 Inf 1 1
Inf 1 Inf Inf
Inf Inf Inf Inf