【问题标题】:MATLAB: error Subscripted assignment dimension mismatchMATLAB:错误下标赋值维度不匹配
【发布时间】:2023-04-05 04:23:02
【问题描述】:

我不断收到 x_values 行的错误“下标分配维度不匹配”。我试过换括号,但我无法弄清楚。我对 MATLAB 不是很好,而且这段代码很长,所以我不想发布整个内容。

for m = 1:num_part;
    for n = 2:num_steps;
    x_values(m,n) = x_values(m,n-1)+ stride_length .* (cos(step_angle(m,n)));
    y_values(m,n) = y_values(m,n-1)+ stride_length .* (sin(step_angle(m,n)));
    r_values (m,n) = sqrt(x_values(m,n).^2 + y_values(m,n).^2);
    if bound_cross(m)~=0;
        continue;
    elseif bound <= r_values(m,n);
            bound_cross (m,1) = n;
    end
end

【问题讨论】:

  • 您能提供您使用的示例输入数据吗?
  • num_part = input('粒子数:');我使用了 1000 num_steps = input ('步数:');我用了 100 stride_length = input ('步幅长度:');我用了 1 bound = input('input bound: ');我用了 20 bound_cross = [num_part, 1] ;

标签: matlab


【解决方案1】:

我发现,变量bound_cross 中有错误。如果您以您在评论中回复的方式将其定义为“bound_cross = [num_part, 1]”,则它仅创建一个 1*2 元素矩阵。但是如果你需要一个 20*1 的矩阵,你必须专门定义它。为了检查代码,我使用了一个空矩阵,它工作正常。

num_part = 20;
num_steps = 1000;
stride_length = 100;
bound = 1;
bound_cross = ones(num_part, 1) ;
x_values = zeros(num_part, num_steps);
y_values = x_values;
r_values = x_values;
step_angle = x_values;

for m = 1:num_part;
    for n = 2:num_steps;
        x_values(m,n) = x_values(m,n-1)+ stride_length .* (cos(step_angle(m,n)));
        y_values(m,n) = y_values(m,n-1)+ stride_length .* (sin(step_angle(m,n)));
        r_values (m,n) = sqrt(x_values(m,n).^2 + y_values(m,n).^2);
        if bound_cross(m)~=0;
            continue;
        elseif bound <= r_values(m,n);
            bound_cross (m,1) = n;
        end
    end
end

【讨论】:

  • 现在我收到此错误-“尝试访问 bound_cross(3);索引超出范围,因为 numel(bound_cross)=2。如果 bound_cross(m)~= 0; "
  • 您的 bound_cross 定义仍然存在错误。因为上述代码中的 m 从 1 变为 20。但正如错误消息所说“numel(bound_cross)=2”,bound_cross 中只有 2 个元素。当 m 变为 3 时,您的代码中没有称为 bound_cross(3) 的元素,因为当前只有 2 个元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
相关资源
最近更新 更多