Can Matlab cellular functions -like cellfun- work with non linearly spaced indices ?
Show older comments
Hi,
I would like to affect a value to some non linearly indexed elements of a vector with using a cell array.
At the moment I index a for loop with a non linearly spaced row index. Let's say :
N = 8;
id = find(randi(2,1,N)-1); % non zeros positions in a random vector of binaries
u = true(1,N);
for k = id
u(1,k:k:end) = false;
end
How would I do the same affectations with cellfun for instance ?
Thank you for help.
Cheers.
Nicolas
Accepted Answer
More Answers (2)
So you're sieving? What is the real value of N for which you want to solve this problem, and how many values are you trying to sieve out (how many elements does id have?)
N = 8;
id = find(randi(2,1,N)-1) % non zeros positions in a random vector of binaries
u = true(1,N);
for k = id
u(1,k:k:end) = false;
end
multiples = mod(1:N, id.') == 0
toKeep = ~any(multiples, 1)
u
Nicolas Douillet
on 19 Jun 2024
Edited: Nicolas Douillet
on 19 Jun 2024
0 votes
1 Comment
Replacing the loop itself with arrayfun or cellfun will almost certainly only increase CPU time over the direct loop.
The fundamental problem is your sieve doesn't have an analytical expression that can be evaluated; the only way to produce the indices is iteration and the explicit loop is almost certainly going to be faster than any more complex method. All the xxxxfun() functions do is move the loop below the visible user code but it still has to get translated to a loop to actually do the deed....
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!