【问题标题】:How to modify data in MatLab code to be csv file如何将 MatLab 代码中的数据修改为 csv 文件
【发布时间】:2020-06-05 16:19:49
【问题描述】:

我有以下图表。 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】:

    以下内容应该可以帮助您启动并运行:

    % 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
    

    【讨论】:

    • 我遇到此错误未定义函数 'readmatrix' 用于类型 'char' 的输入参数。 TestKShortestPath 数据错误 = readmatrix('your-data.csv');
    • 对不起,我没有意识到这个功能只是在matlab 2019a中添加的。我添加了一个使用 readtable 函数的替代方法,它应该适用于 matlab 2013a 或更高版本。
    • 现在的错误是:未定义的函数或变量'm'。 TestKShortestPath 中的错误(第 24 行)netCostMatrix(sub2ind(size(m), data(:,1), data(:,2))) = data(:,3) 反正我觉得谢谢
    • 如果我将 m 更改为 4(=我的矩阵大小),那么我遇到了这个错误:Error using sub2ind (line 52) Out of range subscript.
    • 抱歉,size(m) 应该是 size(netCostMatrix)。我已经更新了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2022-11-28
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多