How to crop matrices at the maximal non-NaN values and then center the data

3 views (last 30 days)
Hi all,
I am new to MATLAB and I have the following problem:
I have matrices something like:
H(1).matrix = [1 2 3
3 4 5
3 4 4
6 NaN 7
NaN NaN NaN]
H(2).matrix = [3 4 5
5 6 7
4 4 4
NaN 3 3
NaN 4 4
NaN NaN 7]
H(3).matrix = [3 3 3
2 1 3
NaN 1 2]
Now, I see that these matrices all have 3 columns but different row number, first is 5x3, second 6x3, third 3x3, but also within columns they have different row length with actual numbers and not NaN. I see that the longest rows length where each columns have non NaN values is 2 (in the third matrix, the first row and the second row with all non NaN values). So now I want to crop all the matrices to have size 2x3. Then I want to center all these matrices.
Something like:
H(1).matrix = [1 2 3
3 4 5]
H(2).matrix = [3 4 5
5 6 7]
H(3).matrix = [3 3 3
2 1 3]
Then I want to center the data (remove from each element the average of the column it belongs to).
Thank you in advance!

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 20 Apr 2019
Edited: Andrei Bobrov on 21 Apr 2019
M = struct2cell(H);
n = min(cellfun(@(x)find(any(isnan(x),2),1,'first')-1,M));
for jj = 1:numel(H)
H(jj).matrix = H(jj).matrix(1:n,:);
end
or without loop 'for-end'
M = struct2cell(H);
n = min(cellfun(@(x)find(any(isnan(x),2),1,'first')-1,M));
C = cellfun(@(x)x(1:n,:),M(:),'un',0);
H = cell2struct(C,'matrix',2);
  7 Comments
Spresi
Spresi on 21 Apr 2019
Edited: Spresi on 21 Apr 2019
Oh sorry, I did not notice that at all. It works now.. Thank you!!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!