setting object properties value for object array in matlab

后端 未结 3 637
孤街浪徒
孤街浪徒 2021-01-20 02:39

I have created an array of objects and I would like assign a property value in a vector operation without using a for loop. Unfortunately I get an error.

A simplifi

相关标签:
3条回答
  • 2021-01-20 03:00

    I think you'll find your answer here in "Struct array errors." Even though this is a class, similar rules apply.

    Unfortunately missing [] is not the cause, since adding them causes more errors. The cause is that you cannot assign the same value to all fields of the same name at once, you must do it one at a time, as in the following code:

    So you'll need:

    for ii=1:100
      vecMyArray(ii).dblMyProperty1 = ii;
    end
    

    I know it's not satisfying, but I think it at least helps us to definitively understand this error.

    0 讨论(0)
  • 2021-01-20 03:18

    I see what you're trying to do now. Use disperse from the MATLAB File Exchange:

    >> [vecMyArray.dblMyProperty1] = disperse(1:100);
    >> vecMyArray(1).dblMyProperty1
    ans = 
        1
    >> vecMyArray(10).dblMyProperty1
    ans = 
        10
    
    0 讨论(0)
  • 2021-01-20 03:19

    You can use the deal function for exactly this purpose:

    [vecMyArray.dblMyProperty1] = deal(1:100);
    

    See: http://www.mathworks.com/company/newsletters/articles/whats-the-big-deal.html


    Edit: No you can't, actually; that'll set them to all be the vector 1:100.

    0 讨论(0)
提交回复
热议问题