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

 采纳的回答

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

1 个评论

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 个)

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

1 个评论

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 Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by