Plot occurence of each element in an array

12 visualizaciones (últimos 30 días)
Kash022
Kash022 el 2 de Nov. de 2016
Comentada: Guillaume el 3 de Nov. de 2016
Hi,
I have a 16x16 array in which I would like to plot the distribution of the occurence of each element for each row, but somehow the below code snippet does not give me the correct solution. Please help. Thanks!
length = HW(:,1); /* HW is my 16x16 matrix */
for i = 1:size(HW(:,1))
numbers(i) = unique(HW(i,1));
count(i) = hist(length(HW(:,i)),numbers(i));
end

Respuesta aceptada

Guillaume
Guillaume el 2 de Nov. de 2016
Your code commented:
length = HW(:,1); %You're creating a length variable (which has nothing to do with length) which will shadow the length function.
for i = 1:size(HW(:,1)) %size(HW, 1) is more logical and faster
numbers(i) = unique(HW(i,1)); %HW(i, 1) is the first number in row i. unique is just going to return that number.
%in effect your loop is equivalent to:
%number = HW(:, 1);
%clearly not what you want to do
count(i) = hist(length(HW(:,i)),numbers(i)); %makes no sense at all
%either you're trying to index your length variable with HW(:, i) but why (and that'll only work if the numbers in the columns are all strictly positive integers smaller than size(HW, 1)
%or you're trying to use the length function (which will not work because of your length variable). again why?
%furthermore your i index works over the rows and your using it as a column index
end
A simple way of doing what you want would be just one call:
hist(HW.', unique(HW(:)); %transpose HW since hist works on columns not rows.
  2 comentarios
Kash022
Kash022 el 2 de Nov. de 2016
Thanks for the brilliant answer. Is it possible to separate this HW array based on 5 values each having a 1x16 array? i.e I would have 5 histograms for each of the values? Thanks!
Guillaume
Guillaume el 3 de Nov. de 2016
Sorry, I don't understand what you're asking. Please show an example of input and desired output.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by