Logical operations of multi dimensional matrices

Hi,
I am looking for a solution to transform an algorithm with for loop to a faster solution by logical operations.
I have an M(mxmxn) matrix and an n length v vector. So, the M matrix has the same size in the 3rd dimension as the length of the vector. I would like to compare the elements of the M matrix to the value of the vector as follows: M(:,:,i)==v(i)
The output should be an mxmxn size logical.
I know, it is a basic task with a for loop, but I would like to solve it with logical operations to save some computation time.
I would appreciate any suggestion. Thanks.

2 commentaires

Torsten
Torsten le 20 Déc 2022
Comparing doubles for equality is never a good idea because of possible floating point errors.
bzsfarkas
bzsfarkas le 20 Déc 2022
Sorry, my bad. I should check M(:,:,i)>v(i), not equality.

Connectez-vous pour commenter.

 Réponse acceptée

If you do
M == reshape(v,1,1,3)
then MATLAB will implicitly expand the vector across dimension 1 and 2, to do the equality check.

2 commentaires

bzsfarkas
bzsfarkas le 20 Déc 2022
Thank you very much. It looks good.
Won't it use more memory due to the expansion? Later, I would like to expand to 4th dimension and running similar calculations. If reshaping results in a big-size array consuming too much memory, I should try to find more effective way.
Anyway, a high-five goes for you.
I have to admit that I was thinking more about code "elegance" in response to what you were trying to achieve, more so than speed (which you had mentioned) or memory management.
I also have to admit that off the top of my head, I don't know if, under the hood, MATLAB actually expands the vector, or if this is only a notational convenience.
My reshaping solution is faster than a for loop under a pretty wide range of array sizes I just tried, but it was not always faster. You may need to do your own testing for optimization.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by