2

I want to replace the value of the fields in a structure array. For example, I want to replace all 1's with 3's in the following construction.

a(1).b = 1;
a(2).b = 2;
a(3).b = 1;

a([a.b] == 1).b = 3; % This doesn't work and spits out:
% "Insufficient outputs from right hand side to satisfy comma separated
% list expansion on left hand side.  Missing [] are the most likely cause."

Is there an easy syntax for this? I want to avoid ugly for loops for such simple operation.

Memming
  • 1,731
  • 13
  • 25

2 Answers2

5

Credits go to @Slayton, but you actually can do the same thing for assigning values too, using deal:

[a([a.b]==1).b]=deal(3)

So breakdown:

[a.b]

retrieves all b fields of the array a and puts this comma-separated-list in an array.

a([a.b]==1)

uses logical indexing to index only the elements of a that satisfy the constraint. Subsequently the full command above assigns the value 3 to all elements of the resulting comma-separated-list according to this.

Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58
1

You can retrieve that the value of a field for each struct in an array using cell notation.

bVals = {a.b};
bVals = cell2mat( bVals );

AFAIK, you can't do the same thing for inserting values into an array of structs. You'll have to use a loop.

slayton
  • 20,123
  • 10
  • 60
  • 89
  • 2
    you actually can do the same thing for inserting values, using [deal](http://www.mathworks.nl/help/matlab/ref/deal.html): `[a([a.b]==1).b]=deal(3)` – Gunther Struyf Nov 11 '12 at 20:09
  • @GuntherStruyf your answer is great. But it wouldn't make sense to make the original response as answer though. Could you post it as a separate reply (for others)? – Memming Nov 11 '12 at 21:02