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.

 Réponse acceptée

Image Analyst
Image Analyst le 9 Déc 2012

1 vote

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.

Plus de réponses (2)

Azzi Abdelmalek
Azzi Abdelmalek le 9 Déc 2012
Modifié(e) : Azzi Abdelmalek le 9 Déc 2012

0 votes

N=1000000;
X=rand(1,N)*6;
arrayfun(@(x) sum(X(X>x & X<x+1)),1:5)
Greg Heath
Greg Heath le 9 Déc 2012

0 votes

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)

Catégories

En savoir plus sur Mathematics dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by