vectorize this operation - help
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hi guys,
I am trying to vectorize the following operations.
k = [1 10:10:90];
p = 10:10:100
Note k and p are made up here for the sake of simplicity, but my script up until the point generates a k and p such that k(n) = p(n) + a for all n and constant a.
r = [k' p']
r =
1 10
10 20
20 30
30 40
40 50
50 60
60 70
70 80
80 90
90 100
Now I want to do is using the values in the columns of r as limits (lower and upper), I want to take each row and get
r(1,1):1:r(1,2)
r(2,1):1:r(2,2)
.....
r(end,1):1:r(end,2)
Note, I can't really put this into a matrix because lengths of each row is not always the same. For example,
1:1:10 has 10 elements while 10:1:20 has 11.
Now, I have a vector X_n that goes from n=1 to n=100.
If i do
ind = find(X_n==0)
I can get a list of all the indices in X_n where the value is 0 for that index.
Using that list, I want to specify
intersect(ind,r(1,1):1:r(1,2))
This will output those indices in ind = find(X_n==0) that are the same as in r(1,1):1:r(1,2) (which is just 1:1:10).
So for the first row in r, I want to know which indices 1:1:10 are in ind = find(X_n==0).
And I want to repeat this operation for each row in r with the different integer limits.
Finally, using those indices that matched, on a row by row basis, i want to plug them back into X_n and find the median value.
so if for row 1 of r, ind and 1:1:10 matches [1 5 7 8 9], I would do median(X_n([1 5 7 8 9])) and put this result as the first element in a new vector, call it sol_med this then gets repeated for each row of r and gets put in the next element of sol_med.
4 comentarios
Jan
el 22 de Sept. de 2011
@Leor: Even with several years of experiences it is hard to predict if vectorization or FOR loops are faster. On one hand this depends on the used Matlab release, on the other hand on the number of processor cores and the amount of RAM. Only one thing is sure: FOR loops benefit from moving all repeated calculations before the loop. And the automatic loop acceleration by the JIT is more efficient, if only elemantary calculations are performed inside the loop. Calling other M-files like MEAN impedes the JIT - inline it by SUM(X)/size(X,1).
Respuestas (1)
Honglei Chen
el 22 de Sept. de 2011
Hi Leor,
You may be able to use arrayfun to do this.
>> doc arrayfun
HTH
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!