Fuad Numan
Fuad Numan

Reputation: 94

MATLAB boxplot of high dimensional vectors with different lengths

I have been looking for a way to use boxplot for different length vectors. thanx for stackoverflow helpers, they give this solution:

A = randn(10, 1); B = randn(12, 1); C = randn(4, 1);
g = [repmat(1, [10, 1]) ; repmat(2, [12, 1]); repmat(3, [4, 1])];
figure; boxplot([A; B; C], g);

unfortunately, my data contains over 100 vectors with different lengths, I wonder if it can be done without repeating the repmat for over 100 times.

Upvotes: 0

Views: 338

Answers (1)

Ikaros
Ikaros

Reputation: 1048

As long as your vectors have different lengths, store it in a cell array.

There are plenty was of doing it, here are 3 examples

1) "Naive" for loop

g = [];
vars_cell = {A, B, C, ....};

for it = 1 : length(vars_cell)
    g = [g; repmat(it,size(vars_cell{it}))];
end

This way of doing it works but is very slow with big quantites of vectors or big vectors! It comes from the fact that you are re-defining g at each iteration, changing its size each time.

2) Not-naive for loop

vars_cell = {A, B, C, ....}; 

%find the sum of the length of all the vectors
total_l = sum(cellfun(@(x) length(x),vars_cell));

g = zeros(total_l,1);
acc = 1;

for it = 1 : length(vars_cell)
    l = size(vars_cell{it});
    g(acc:acc+l-1) = repmat(it,l);
    acc = acc+l;
end

This method will be much faster than the 1st one because it defines g only once

3) The "one-liner"

vars_cell = {A, B, C, ....}; 
g = cell2mat(arrayfun(@(it) repmat(it, size(vars_cell{it})),1:length(vars_cell),'UniformOutput',0)'); 

This is qute equivalent to the 2nd solution, but if you like one line answers this is what you are looking for!

Upvotes: 1

Related Questions