Matlab/Simulink中mxArray转double报错及解决方法
问题背景与报错
我需要开展街道与路口仿真,车辆路径规划在Matlab外部完成,路线数据存储于CSV文件中。需根据车辆的destination_ID从表格中读取next_knot_ID,以此设置车辆的下一个行驶节点。
尝试使用readtable和readcell读取表格时,遇到两类报错:
- “Function output 'y' cannot be an mxArray in this context. Consider preinitializing the output variable with a known type.”
- “Brace indexing is not supported for variables of this type.”
最初的测试代码如下:
function y = fcn() coder.extrinsic('readtable'); % 使Matlab函数可在Simulink中运行 temp=readtable("test.xlsx"); % 读取表格 temp2=temp(1:1,1:1); y = temp2;
此时temp的数据类型为mxArray,尝试多种输出方式均触发上述报错。当前函数输出仅连接Simulink的Display模块,仅需next_knot_ID的数值型结果。
解决方案
针对两类报错,对应解决方法如下:
- 针对报错1:预先初始化输出变量
y为已知类型,例如设置y = 0.0(双精度标量)。 - 针对报错2:将表格或单元格转换为数组,使用
table2array(对应readtable)或cell2mat(对应readcell)转换后读取数值。
可行代码示例
使用readtable的实现
function y = fcn() % 使Matlab函数可在Simulink中运行 coder.extrinsic('readtable'); filepath = 'test.xlsx'; % 同样支持.csv格式文件 range = 'B2:C3'; y = 0.0; % 初始化为双精度标量 % 读取文件 temp = readtable(filepath,Range=range); % 将表格转换为数组 temp2 = table2array(temp); % 提取目标位置的数值 index = 1; % 目标数据在数组中的索引位置 temp3 = temp2(index); y = temp3;
使用readcell的实现
function y = fcn() % 使Matlab函数可在Simulink中运行 coder.extrinsic('readcell'); filepath = 'test.xlsx'; % 同样支持.csv格式文件 range ='B2:C3'; y = 0.0; % 初始化为双精度标量 % 读取文件 temp = readcell(filepath,Range=range); % 将单元格转换为数组 temp2 = cell2mat(temp); % 提取目标位置的数值 index = 1; % 目标数据在数组中的索引位置 temp3 = temp2(index); y = temp3;
不推荐的xlsread实现(仅供参考)
function y = fcn(c) coder.extrinsic('xlsread'); filepath='test.xlsx'; range='B2:B2'; y = 0.0; % 初始化为双精度标量 % 虽原理理解不深,但可正常运行 [temp, ~ , ~] = xlsread('test.xlsx', range); y = temp;
内容的提问来源于stack exchange,提问作者user23303680
相关产品推荐
相关产品推荐

