Compare matrix column-wise with vector

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

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 22 日

4 投票

mask=bsxfun(@lt,mat,minVec)| bsxfun(@gt,mat,maxVec)

1 件のコメント

Philip Ohnewein
Philip Ohnewein 2013 年 11 月 22 日
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!

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2013 年 11 月 22 日

0 投票

Try this:
[rows, columns] = size(mat)
mask = mat < repmat(minVec, [rows, 1]) | mat > repmat(maxVec, [rows, 1])

1 件のコメント

Philip Ohnewein
Philip Ohnewein 2013 年 11 月 22 日
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.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by