help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: strange struct syntax


From: Markus Mützel
Subject: Re: strange struct syntax
Date: Wed, 5 May 2021 11:28:00 +0200

Am 05. Mai 2021 um 10:44 Uhr schrieb "Francesco Potortì":
> I read the manual, and as far I understand, this is documented as it
> is.  Yet, it looks very strange and adds to the difficulty of mastering
> the syntax of cell arrays and structures, so I am asking for further
> confirmation. 
> 
> Is this perfectly normal?
> 
> 
> octave> a={"Name Surname"}
>   a =
>   {
>     [1,1] = Name Surname
>   }
> 
> octave> a(1)
>   ans =
>   {
>     [1,1] = Name Surname
>   }
> 
> ## Now, I want to create a struct with only one field, which is a cell
> ## array of strings.
> 
> ## This one works alright
> octave> clear s
> octave> s.names = a(1)
>   s =
>     scalar structure containing the fields:
>       names =
>       {
>         [1,1] = Name Surname
>       }
> 
> ## This one does not.  The manual explains why
> octave> s = struct("names", a(1))
>   s =
>     scalar structure containing the fields:
>       names = Name Surname
> 

You are right: If the struct constructor is called with cell array input, a 
struct array with the same size of the cell array is created. The fields of the 
elements in the struct array have the value of the respective cell array.
The cell array has the size 1x1, so the resulting struct array has the size 
1x1. The first element in the cell array is `a{1}` which is a character array.

> ## This one does what I want.  Completely  unintuitive to me
> octave> s = struct("names", { a(1) })
>   s =
>     scalar structure containing the fields:
>       names =
>       {
>         [1,1] = Name Surname
>       }
> 

This is basically the same as before: The struct constructor is called with a 
cell array (`{ a(1) }`). The cell array has the size 1x1, so the resulting 
struct array has the size 1x1. The first element in the cell array is `a(1)` 
(as opposed to `a{1}` in the example before). So the value of `s.names` is 
`a(1)` which is a 1x1 cell array.

HTH,
Markus




reply via email to

[Prev in Thread] Current Thread [Next in Thread]