Efficiently find indices in matrix

Massive edit/complete rewording by example.
if true
A = [1:10];
for i = 1:10,
for j = 1:10,
c(i,j) = a(i)-a(j);
end
end
map = c == %%%;
init = a;
initval(~map) = nan;
initval(isnan(initval)) = 0;
uval = unique(initval);
end
Where %%% is a placeholder for "if that element in c is divisible by 5", a condition I'm not sure how to put in efficiently yet. Oversimplified, but gets the idea across. I have a large vector (not all consecutive integers, a bunch of random numbers) that I'm essentially subtracting from itself element by element and am looking for every value in that resulting matrix that is a multiple of 5. Then, I want it to tell me the values from A that "generated it", ie 1 6 2 7 3 8 4 9 etc.
Any suggestions?
Thanks for looking.

 Accepted Answer

Regarding your new question
map = mod(c,5) == 0
valuesThatGeneratedIt = c(map)
But make sure they're all integers or you may not get 0 exactly. See the FAQ.

1 Comment

Awesome, thank you so much. Sorry it took so long to get back to you...I was away from the internet for quite some time.

Sign in to comment.

More Answers (1)

Why don't you just make a logical (binary) "map" of where C meets your criteria? For a simple example, let's find out where C is -10:
binaryMap = C == -10; % map of where C = -10.
(If you want to take a histogram and find negative values of C that occur at least twice, then you can do that with a different criteria, a little more complicated.) Now you had to create 2D matrices to add A and B (using repmat or whatever) to get C. So you can just use the same indexes to get the A Values or B values. for example mask A like this:
AmatchingConditions = A; % Initialize.
AmatchingConditions(~binaryMap) = nan; % Set non-matching locations to nan
Now when you look at A, only the elements in A that match your criteria will appear and those that don't contribute to matching your criteria will appear as nan.

Categories

Community Treasure Hunt

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

Start Hunting!