You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

尝试创建含5个子图的单图(gamma步长1迭代)报错,求排查

MATLAB错误排查:Brace indexing is not supported for variables of this type

错误原因分析

  1. 索引类型不匹配:代码中premium是数值数组(每次循环被覆盖为当前gamma对应的一维数组),但尝试用cell数组的花括号{i}索引,MATLAB不支持对数值数组使用花括号索引,因此报错。
  2. 循环逻辑错误:外层gamma=1:5循环内嵌套了i=1:5的子图循环,导致每次gamma迭代都会新建一个figure,且子图重复绘制当前gamma的结果,无法实现“单图5个子图对应不同gamma”的需求。
  3. 数据未持久化:每次循环中premium被直接覆盖,没有保存所有gamma对应的计算结果,后续绘图无法调用不同gamma的数据。

修正方案

  1. 初始化存储结构:提前创建cell数组或二维数组,保存每个gamma对应的premium数据。
  2. 拆分循环逻辑:先完成所有gamma的计算并存储结果,再单独执行绘图逻辑,创建一个figure并绘制5个子图。
  3. 修正索引方式:根据存储结构的类型,使用正确的索引(cell数组用{i},数值数组用(:,i))。

修正后的完整代码

clear all; close all; clc;

%% 参数定义
rho = 1;
k0 = 1;
K = 1;
y1 = 0.1;
mu = 0.06;
mu0 = 0.06;
sigma0 = 0.15;
sigmae = 0.1;
beta = 1-(1-0.04)/252;
sigmaS = linspace(0.05,0.5,100);
precision_S = 1./sigmaS.^2;

% 初始化cell数组存储每个gamma对应的premium结果
premium = cell(5, 1);

%% 循环计算所有gamma对应的premium
for gamma = 1:5
    mbar_plus = mu0+0.01; % 假设公告后情绪上升0.5%
    mbar_minus = mu0;
    sigmahat_plus = sqrt(1./(1/sigma0^2+1/sigmae^2+1./sigmaS.^2));
    sigmahat_minus = sqrt(1/(1/sigma0^2+1/sigmae^2));
    varm_minus = (1/sigmae^2)./(1/sigma0^2+1/sigmae^2)^2;
    varm_plus =  (1/sigmae^2)./(1/sigma0^2+1/sigmae^2+1./sigmaS.^2).^2;

    % 计算公告溢价
    premium_1 = (mbar_plus - gamma.*sigmahat_plus.^2.*K)./(mbar_plus - gamma.*sigmahat_minus.^2.*K);
    premium_2 = (mbar_plus-gamma.*sigmahat_minus.^2*K)./(mbar_minus-gamma.*sigmahat_minus.^2*K).*exp(-(mbar_plus-mbar_minus).*gamma*K);
    premium{gamma} = premium_1.*premium_2; % 用cell数组存储当前gamma的结果
end

%% 绘制单图5个子图
figure('Position', [100, 100, 1200, 300]) % 设置figure大小,适配5个子图
hold on
for i = 1:5
    subplot(1,5,i);
    plot(precision_S, premium{i}, 'Linewidth',2);
    title(['Gamma=' , num2str(i)])
    xlabel('1/\sigma_S^2')
    ylabel('p^+/p^-')
    grid on % 可选:添加网格更清晰
end
sgtitle('Announcement Premium for Different Gamma Values') % 添加总标题
hold off

关键改动说明

  • 将参数中不随gamma变化的部分移到循环外,避免重复计算。
  • 用premium = cell(5,1)初始化cell数组,存储每个gamma对应的一维数组结果。
  • 拆分计算循环和绘图循环,先完成所有数据计算,再一次性绘制所有子图。
  • 调整figure位置和大小,避免子图拥挤;添加总标题sgtitle提升可读性。

内容的提问来源于stack exchange,提问作者SunnyD_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:22:47