Check elements of matrix

16 views (last 30 days)
ahmed ezzat
ahmed ezzat on 9 Dec 2012
i have this program
N=1000000;
t=1;
X=rand(1,N);
for i=0:.1:5
y=(X>=i & X<(i+.1));
s(t)=sum(y);
t=t+1;
end
-----------------------------------
so; i need to check all elements of matrix X against each element in matrix i. is there any method to do this without for loop? i.e. by using matrix notation.

Accepted Answer

Image Analyst
Image Analyst on 9 Dec 2012
Have you realized that you're simply calculating the histogram and that there is a function for that called histc()? Here, do it this way instead:
binEdges = 0 : 0.1 : 5;
counts = histc(X, binEdges);
Here, my counts is the entire histogram, basically the same as your s except that you calculated s for only 5 bins.
If you say " but we're not allowed to use any built-in functions" then please tag this as homework.

More Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 9 Dec 2012
Edited: Azzi Abdelmalek on 9 Dec 2012
N=1000000;
X=rand(1,N)*6;
arrayfun(@(x) sum(X(X>x & X<x+1)),1:5)

Greg Heath
Greg Heath on 9 Dec 2012
Matrices can be compared using <, =, or > only if they have the same dimensions or at least one is a scalar.
Note that
X < 1
Therefore
y = 0 for i > 1.
Consequently, the following makes more sense:
t=0
for i=0:0.1:1 % NOT 5
t =t + 1 % Update at beginning of loop
y = ...
s(t) = ...
end
Hope this helps.
Thank you for formally accepting my answer.
Greg
P.S. An alternative is to use 0: 0.1 :5 with X = 5*rand(N)

Community Treasure Hunt

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

Start Hunting!