MATLAB Answers

Delete end points from columns in a structure array

3 views (last 30 days)
SS
SS on 27 Nov 2019
Commented: SS on 27 Nov 2019
Hello.
I have a structure array S (1 x 50000) with 10 fields. The elements in the fields are column matrices (1 X M) with their size consistent for given S(i).
I want to delete tails in all the 10 fields (2 data points on each side - at the beginning and the end of the vector) which, should result in the array size of (1 X M-4).
For example, the input is something like this
S(1).f1=[1,2,3,4,5,6,7,8,9,10];
S(1).f2=[2,4,6,8,10,12,14,16,18,20];
S(2).f1=[10,20,30,40,50,60,70];
S(2).f2=[150,200,250,300,350,400,450];
I want the output to be,
S(1).f1=[3,4,5,6,7,8];
S(1).f2=[6,8,10,12,14,16];
S(2).f1=[30,40,50];
S(2).f2=[250,300,350];

  0 Comments

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 27 Nov 2019
S = cell2struct(cellfun(@(x)x(3:end-2),struct2cell(S),'un',0),fieldnames(S));

  3 Comments

SS
SS on 27 Nov 2019
Thank you, it works well. I have an additional step here, I want to delete the fields whose size is less than 5. From the example in the question, I want to delete S(2) and all such S(i) whose length is less than 5. I have tried using this for loop,
for i=1:numel(S)
if size(S(i))<5
S(i)=[ ]
else
S(i)=newS(i)
end
end
It didn't work
Andrei Bobrov
Andrei Bobrov on 27 Nov 2019
S(any(cellfun(@numel,struct2cell(S)) < 5)) = []

Sign in to comment.

More Answers (1)

Luna
Luna on 27 Nov 2019
Edited: Luna on 27 Nov 2019
I did something like this:
newS2 = arrayfun(@(y) structfun(@(x) x(3:end-2),y,'uni',false),S)
Or:
for i = 1:numel(S)
newS(i) = structfun(@(x) x(3:end-2),S(i),'UniformOutput',false)
end

Sign in to answer this question.


Translated by