How do I fill empty Matrix elements with NaNs?
Show older comments
Hello,
I have a matrix that looks something like this:
A =
struct with fields:
CC: 12.4102
CD: [2×1 double]
CO: [4×1 double]
CV: [5×1 double]
LA: [7×1 double]
FB: []
....
The Matrix A contains around 160 vectors that range from length 0 (empty) to length of 7.
Because I need to work with the values, in this case plot them and calculate mean, the vectors within the matrix need to have the same length.
How can I extend every vector to be the length of 7 and fill those new elements with NaNs?
It is important that the vectors keep their original name! Their order is not important.
I tried iterating through each matrix element, but could not get any further than this:
for idx = 1:numel(A)
element = A(i);
%do operation
end
Accepted Answer
More Answers (1)
Fake data:
>> A.a = rand(4,1);
>> A.b = [];
>> A.c = rand(7,1);
>> A.d = rand(10,1);
>> N = max(structfun(@numel,A)); % or 7, as you prefer.
>> F = @(v)[v;nan(N-numel(v),1)];
>> B = structfun(F,A,'UniformOutput',false)
B =
scalar structure containing the fields:
a =
0.061883
0.186276
0.093157
0.819494
NaN
NaN
NaN
NaN
NaN
NaN
b =
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
c =
0.494865
0.747194
0.876034
0.597573
0.201666
0.014505
0.726006
NaN
NaN
NaN
d =
0.916148
0.136177
0.749379
0.973931
0.035588
0.379591
0.640495
0.961396
0.673465
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!