How do I fill empty Matrix elements with NaNs?

14 Ansichten (letzte 30 Tage)
JP
JP am 23 Nov. 2019
Bearbeitet: Stephen23 am 23 Nov. 2019
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

Akzeptierte Antwort

Bhaskar R
Bhaskar R am 23 Nov. 2019
% assuming a fake structure similor to your case
A.a = rand(4,1);
A.b = [];
A.c = rand(7,1);
A.d = rand(10,1);
fields = fieldnames(A); % get fields
for ii =1:length(fields)
if length(A.(fields{ii})) <=6 % retaining as it is for length 7
% append nan's
A.(fields{ii}) = [A.(fields{ii}); nan(7 - length(A.(fields{ii})),1)];
% plotting
figure, plot(A.(fields{ii})), title(['Vector : ', fields{ii}]);
end
end
% mean value of each vector of structure
mean_values = structfun(@nanmean,A, 'uniform', false);

Weitere Antworten (1)

Stephen23
Stephen23 am 23 Nov. 2019
Bearbeitet: Stephen23 am 23 Nov. 2019
Fake data:
>> A.a = rand(4,1);
>> A.b = [];
>> A.c = rand(7,1);
>> A.d = rand(10,1);
Then you can simply use structfun.
>> 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

Kategorien

Mehr zu Operators and Elementary Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by