Extracting arrays from a structure - different number of array elements

1 Ansicht (letzte 30 Tage)
I am having problems extracting arrays from a structure that I created. One of the fields returns a different number of values.
Hypo2 =
1×161 struct array with fields:
datim
otime
file
volctype
lat
lon
dep
mag
>> size( Hypo2 )
ans =
1 161
>> size( [Hypo2.datim] )
ans =
1 161
>> size( [Hypo2.mag] )
ans =
1 160
Hypo2.mag contains numeric values and I'm guessing that there is a NaN in one of them.
How can I extract the arrays so that they are all of the same size? I thought that [] was the way to do it.
I attach a mat file with Hypo2 - there are more fields than I listed above.

Akzeptierte Antwort

Stephen23
Stephen23 am 5 Apr. 2023
Bearbeitet: Stephen23 am 5 Apr. 2023
"I'm guessing that there is a NaN in one of them."
A NaN is scalar, so would not cause this. However an empty array could cause this:
S = load('Hypo2.mat');
H = S.Hypo2;
unique(cellfun(@numel,{H.datim})) % all scalar
ans = 1
unique(cellfun(@numel,{H.mag})) % some are empty
ans = 1×2
0 1
"How can I extract the arrays so that they are all of the same size?"
You would have to either
  1. use a container array (e.g. a cell array or structure array) to hold the differently-sized data,
  2. or you would have to ensure the data are the same sizes (e.g. by modifying the data before concatenating or by padding&rearranging the data after concatenating together). For example:
X = cellfun(@isempty,{H.mag});
[H(X).mag] = deal(NaN);
V = [H.mag]
V = 1×161
2.8000 2.3000 2.0000 1.6000 1.9000 1.3000 1.2000 1.0000 1.9000 2.3000 1.4000 1.3000 1.8000 1.3000 1.9000 1.4000 1.3000 1.6000 2.0000 1.4000 1.7000 1.5000 1.8000 2.4000 1.5000 1.6000 1.4000 1.8000 1.9000 1.1000
"I thought that [] was the way to do it."
Square brackets are a concatenation operator. If the sizes of the things being concatenated together are different, why should the concatenation operator magically make them the same size? How would it even know what size you expect the output to be (except by using the sizes of the input data... which is exactly what it does now). Why should these be the same size?:
[0,1,2]
ans = 1×3
0 1 2
[0,[],2]
ans = 1×2
0 2
See also:
  1 Kommentar
dormant
dormant am 6 Apr. 2023
Thank you for the detailed explanation. Sometimes I use operators and functions without knowing exactly how to use them. It works for a while, but then suddenly I'm stumped.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by