MATLAB: How to assign the values of the same field in an array of structures in one line

MATLAB: How to assign the values of the same field in an array of structures in one line

MATLAB

Given an array of stuctures such as the following one,
sArray(1).var1 = 1;
sArray(2).var1 = 1;
how can I assign the values of var1 in both elements of the array in one line to have values below?
sArray(1).var1 = 3;
sArray(2).var1 = 4;

Best Answer

  • This is possible by the combined use of the operator ‘[]’ and function ‘deal’. For the aforementioned example the solution would be the following one:
    >> [sArray.var1] = deal(3, 4);
    >> sArray.var1
    ans =
    3
    ans =
    4
    Note the necessity of using the operator ‘[]’ herein because the expression [sArray.var1] is a comma seperated expression.
  • Add a Comment

    Your email address will not be published. Required fields are marked *