1

I have .mat file format that I want to modify to pass to another software. the file has 1x1 struct (name:data) with 4 fields. one of them is a 1x15 struct (name: event) with another 4 fields. I want to modify these fields. For example, the first one is 'time' which I tried to modify in different ways:

data.event.time=[1:15];

and I get the error:

"Scalar structure required for this assignment"

Also tried:

data.event = setfield(data.event,'time',1:15);

and got:

 "Scalar structure required for this assignment.

Error in setfield (line 33)
    s.(deblank(strField)) = varargin{end};"

I know that I don't understand the mechanism of structures on Matlab so my question might be kinda stupid but it is my second time to use it.

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
  • What is that structure? there is missing information here. If you do `a.b.c=[1:15]` it works perfectly, so it is something about that structure that is blocking you from doing that. – Ander Biguri Sep 29 '16 at 11:14
  • Sorry, but what do you mean with "what is that structure". I mean what could be the missing information? – KnowsNothing Sep 29 '16 at 11:20

2 Answers2

2

You are probably looking for this:

for t=1:15
    data.event(t).time=t;
end

If you have a vector that you want to assign to multiple elements of a struct, a loop is the easiest way.

Unfortunately there does not appear to be a nice way to directly assign elements of a vector to elements of a struct.

It's probably possible without a loop if you change your vector to a cellarray, but I personally find that counterintuitive.

Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122
1

As already suggested by Dennis Jaheruddin, you can avoid a for loop by converting to a cell array and using the builtin deal function as follows:

timeCell = num2cell(1:15);
[event.time] = deal(timeCell{:});

You need to convert to a cell array, because you want to use the different vector elements as arguments for the deal function.

Community
  • 1
  • 1
m7913d
  • 10,244
  • 7
  • 28
  • 56
  • This worked for a cell array of strings: `timeCell = {'A1', 'A2', 'A3'}` – Lucas Jan 27 '22 at 03:17
  • 1
    Actually, `deal` worked directly, with no need for a cell array first. `[event.time] = deal('A1', 'A2', 'A3')` – Lucas Jan 27 '22 at 03:25