Plot occurence of each element in an array

8 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2016-11-2
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 个评论
Kash022
Kash022 2016-11-2
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 2016-11-3
Sorry, I don't understand what you're asking. Please show an example of input and desired output.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by