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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

you actually can do the same thing for inserting values, using deal: [a([a.b]==1).b]=deal(3)
@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)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.