Dear all,
I have an mxn matrix and a 1xn vector I want to compare each ith column of the matrix with the ith value of the vector. The result should be an mxn logical matrix to be used
Example:
minVec = [ 0 2 0];
maxVec = [10 10 9];
mat = [-1 2 5;
9 15 3];
I would like to calculate the following, but without a for-loop...
mask(:,i) = mat(:,i)<minVec(i) | mat(:,i)>maxVec(i);
mask = [ 1 0 0;
0 1 0]
I guess there must be some solution using arrayfun, perhaps?
Any help is greatly appreciated!
Thank you very much, Philip

 Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 22 Nov 2013
mask=bsxfun(@lt,mat,minVec)| bsxfun(@gt,mat,maxVec)

1 commentaire

Oh, wow, what an elegant, simple and fast solution: works like a charm, thank you very much! I didn't even know that a function called bsxfun exists... Well, I'm a newbie, after all... :-)
I have another somehow similar problem, maybe this can be solved in a similar way? Here it is:
Given mx1 vector 'vec' and 1xn vector 'threshholds', I want to construct an 1xn vector 'minIdx': minIdx(i) should contain the index of the element of vec that is closest to threshholds(i), but greater than thresh(i). Example:
vec = [3 4 5 6 7 8]';
threshholds = [4.5 3];
minIdx = [3 2]
I guess this is possible again using bsxfun or arrayfun or something like that. I am currently doing it with some repmats, but I don't really like that...
Thank you very much!

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 22 Nov 2013
Try this:
[rows, columns] = size(mat)
mask = mat < repmat(minVec, [rows, 1]) | mat > repmat(maxVec, [rows, 1])

1 commentaire

Philip Ohnewein
Philip Ohnewein le 22 Nov 2013
Thank you, this works. I was actually using a similar code, but needed a better solution, because the use of repmat is both slow and very memory hungry, since mat has a huge number of rows, about 10^6.
That's why I was looking for some more efficient code.

Connectez-vous pour commenter.

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by