【问题标题】:How to store objects in a vector?如何将对象存储在向量中?
【发布时间】:2014-08-24 12:50:37
【问题描述】:

基本上我想做的是定义一个空向量,然后在 for 循环中用一些对象填充它,比如

status = [];
while(sweepLine.y > 0)
    for i = 1 : m
       isSweeped = IsBeingSweeped(Sections(i), sweepLine);
       if(isSweeped == 1)
       status(i) = Sections(i);
     end
     sweepLine.y = sweepLine.y - 1;
 end

但是,matlab 只是简单地告诉我错误,例如, 从 Section 转换为 double 时发生以下错误: 使用双重错误 无法从 Section 转换为 double。

tryGOX 中的错误(第 41 行) status(i) = Sections(i);

如果我想在 Java 中做同样的事情,我可能会写

Section[] status = new Section[10];
while(sweepLine.y > 0){
    for(int i = 0; i < 10; i ++){
       isSweeped = IsBeingSweeped(Sections[i], sweepLine);
       if(isSweeped == 1)
       status[i] = Sections[i];
     }
    sweepLine.y = sweepLine.y - 1;
 }

我如何在 Matlab 中做到这一点?

谢谢

【问题讨论】:

  • 您是否缺少endif 声明?

标签: matlab


【解决方案1】:

有很多缺乏的信息。一些猜测:

status 是一个函数。不要将其用作变量。如果错误仍然存​​在,请更改其名称并尝试。

你说Sections 包含对象。您不能将对象存储在双精度数组中。请改用cell array

sectionStatus{i} = Sections(i);

甚至更好:

sectionStatus{ii} = Sections(ii);

因为i 是虚数单位,当你覆盖它时可能会引起麻烦。 (虽然在较新版本的 Matlab 中没有那么多麻烦,如果有的话)。


更复杂一点的方法是使用 structs

getobjname = @(x) inputname(1);
sectionStatus = struct;

while(sweepLine.y > 0)
    for ii = 1 : m
       isSweeped = IsBeingSweeped(Sections(ii), sweepLine);
       if(isSweeped == 1)
          sectionStatus.( getobjname(Sections(ii)) ) = Sections(ii);
       end
       sweepLine.y = sweepLine.y - 1;
    end
 end

这将为您提供一个包含所有部分的结构,其中包含类实例的名称。我猜这实际上是变量Sections 的构建方式。

【讨论】:

    【解决方案2】:

    如果你知道大小,你可以预先分配。

    status= zeros(size);
    

    干杯

    【讨论】:

      【解决方案3】:

      理想情况下,如果您知道可以做到的尺寸:

      status = zeros(N);
      

      或:

      status(N) = 0;
      

      如果你不知道大小,那么在你的for循环中,你可以写:

      status(end+1) = Sections(i);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-24
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2021-03-10
        • 2018-09-17
        相关资源
        最近更新 更多