Simulink中bwboundaries代码生成报错,如何修改代码解决?
问题与解决方案:Simulink代码生成类型不匹配错误
问题背景
已在Simulation Target>Advanced中启用动态内存分配,默认阈值设为0,运行以下MATLAB代码时触发错误:
B={{nan}}; %%Defining so that it can be set as size variable. coder.varsize('B',[50 1]); B={B;bwboundaries(BW,'noholes')} %%Not B{:}=bwboundaries() as multiple inputs are not allowed Y=B{2} boundary=Y{2}
错误信息
=== Simulation (Elapsed: 1:21 min) === Error:Simulink does not have enough information to determine output sizes for this block. If you think the errors below are inaccurate, try specifying types for the block inputs and/or sizes for the block outputs. Error:This assignment writes a 'cell' value into a 'double' type in element '{1}{1}'. Code generation does not support changing types through assignment. Check preceding assignments or input type specifications for type mismatches. Function 'Image Processing System/corner_detection' (#95.612.613), line 21, column 1: "B" Launch diagnostic report. Error:Errors occurred during parsing of MATLAB function 'flightControlSystem/Image Processing System/corner_detection' Error:Simulink cannot determine sizes and/or types of the outputs for block 'flightControlSystem/Image Processing System/corner_detection' due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs. Error:Simulink cannot determine sizes and/or types of the outputs for block 'flightControlSystem/Image Processing System/corner_detection' due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
解决方案
错误核心是嵌套cell与普通cell的类型不匹配:原代码初始化B={{nan}}为嵌套cell(cell内包含cell),后续拼接bwboundaries返回的普通cell数组时,导致元素类型冲突,代码生成不允许这种类型变更。修改步骤如下:
- 直接初始化
B为普通cell数组,无需嵌套结构 - 保留
coder.varsize声明以支持动态大小 - 直接赋值
bwboundaries的结果到B,避免不必要的拼接 - 添加边界检查,防止索引越界
修改后的代码:
% 初始化B为普通cell数组,匹配bwboundaries返回的坐标类型 B = {[]}; % 声明B为动态大小的cell数组,最大尺寸[50 1] coder.varsize('B', [50 1]); % 直接将bwboundaries的结果赋值给B B = bwboundaries(BW, 'noholes'); % 提取第二个边界(添加检查避免索引越界) if length(B) >= 2 boundary = B{2}; else boundary = []; end
关键说明
- 去掉嵌套cell初始化,彻底解决类型冲突问题:
bwboundaries返回的是存储坐标数组的cell数组,直接赋值即可 - 添加边界检查,符合代码生成的严谨性要求,避免运行时索引错误
- 保留
coder.varsize声明,确保Simulink识别动态内存分配需求
内容的提问来源于stack exchange,提问作者space_monkey
相关产品推荐
相关产品推荐

