Wednesday, March 27, 2024

Compiling Matlab Mex Files in Visual Studio

 Going back and forth between Matlab and other languages is a must if you need to save time using either your code written in other languages (in my case here C++) or using pre-built libraries.

I struggled a lot, trying to use loadlibrary command in Matlab to execute some commands from a dll, either Matlab doesn't find the function in the library, or with compatibility issues and so many other problems.

So I went on to use mex functions. It was going OK in Matlab till I needed to use libraries that are based on libraries that are based on other libraries, and the client has an older version of Matlab with an old system.

It became complex and debugging to know the error was a problem for an inexperienced programmer like me.

So I went to use the ability to compile mex files in Visual Studio, where the Environment is already setup for all the old libraries and I need only to do some project configurations, and it worked :).

I am writing this right now to first help myself document this to use in the future, and maybe someone else is having the same struggle as me, and this can help to find the way.

My setup used in this article is Matlab R2015b, VS2017, Win 7.

The first thing I did is to search for suitable configurations to build mex files in VS, I found many pages on the internet, 2 methods were the ones that really helped me:

Method 1: using the steps in How to build mex file directly in Visual Studio?

Method 2: using the steps in MEX Function Templates


Method 1:  Setting the configurations manually 

Knowing which configurations affect your project is good knowledge to have, this is why I am explaining this method first, if you want a faster solution go to Method 2.

Start an empty C++ project with the following settings in the project's Property Pages to build a working .mex function from Visual Studio, remember to repeat these for your different project build configurations (debug and release for example if needed):


1 - Configuration properties -> General:
    Set Target Extension to .mexw32 (or .mexw64 depending on your environment)
    Set Configuration Type to Dynamic Library (.dll)


2- Configureation poperties -> VC++ Directories:

    Add $(MATLAB_ROOT)\extern\include; to Include Directories


Configuration properties -> Linker -> General:

    Add $(MATLAB_ROOT)\extern\lib\win64\microsoft; to Additional Library Directories


Configuration properties -> Linker -> Input:

    Add libmx.lib;libmex.lib;libmat.lib; to Additional Dependencies


Configuration properties -> Linker -> Command Line:

    Add /export:mexFunction to Additional Options

$(MATLAB_ROOT) is the path to Matlab's root folder, eg. C:\Program Files\MATLAB\R2013a.


So far this has only been tried from a solution created from scratch and built for Matlab 2013a 64-bit. I assume that to build for 32-bit one only needs to change both occurrences of 64 to 32. I will update the post when I have confirmed that this works for an existing solution.


EDIT: As expected this works for projects added to existing solutions. Remember to set the new project to be dependent on the project that creates the library.


Edit 2: Following this question I can confirm that the above steps work in Visual Studio 2012, 2013, and 2017 too.

Links that may help:

Visual Studio Toolbar for mex interface with video tutorial

Compiling a MEX file with Visual Studio

How to build mex file directly in Visual Studio


Problems accessing Git Repo with SSH key using Tortoise Git

 I had suffered for few days of the Access denied Problem when trying to access my Repository through Tortoise Git. I could clone repositories fine with VSCode and update them without problems, but using Tortoise Git I had always the access denied Problem.

after searching a lot on the web, the only solution that worked for me was to change the SSH client used by Tortoise Git, to the same client used by the System Git it self, which in my case was in :C:\Program Files\Git\usr\bin\ssh.exe,

in your case it may be different, or you could use C:\Windows\System32\OpenSSH\ssh.exe

the full thread on stackoverflow is at https://stackoverflow.com/questions/13516119/tortoisegit-with-openssh-key-not-authenticating-using-ssh-agent

Wednesday, March 9, 2022

Visual Studio, can't find header file

I had a strange problem with VS 2017, where many errors of "cannot find source file xxxx.h" although they are in search path and in incluse vc++ directories of the project.
After some search on the internet, what worked for me is deleting the ".vs" folder of the whole solution after closing VS and starting VS again so the IDE can recreate the solution db again. 

Tuesday, October 3, 2017

Matlab: Elementwise multiply a 1D vector or a 2D matrix with each slice of a 3D Matrix

I know that an answer to this can be found in many websites like stackoverflow, and actually I am referring to one that has the answer here too. The thing is sometimes having a different wording may help others in search. Also for me as writing about it here will help me memorize and return back to it when needed :)

Matlab is a great tool for numerical computation, but many tricks may be hard to get used too, one of the main features in MATLAB is factorization and using functions like "bsxfun"

I came across a problem that required me to multiply a 2d Matrix by each slice of a 3D matrix, the regular solution for this is to do a For loop and do a simple element wise multiplication for each 2D slice of the 3D Matrix.

another solution is to use "bsxfun" and "permute":

So Assuming you have a matrix A with 3x4 dimensions and a matrix B with 3x4x5 dimensions, you can use :
result = bsxfun(@times, A, B);

or if  you have a vector of A of 5 cells and a matrix B with 3x4x5 dimensions, you can use :
Use bsxfun with permute to align dimensions:

result = bsxfun(@times, permute(vec1,[2 3 1]), mat2);

the original link that I had this solution from is in stackoverflow

Monday, October 5, 2015

Cleaning Debug and release folders in visual studio solutions / projects

Either you need to clean these folders to save space,  make sure that your projects are clean rebuilt, or you have the nasty error :

fatal error C1083: cannot open compiler generated file: 'xxxxxx.xxx': permission denied

 

Searching the internet will give you some results from msdn or stackoverflow , that will mostly work like :

 

MSDN solution .

 

StackOverflow 

 

but the one that worked for me is a small C++ project :

Clean Visual Studio Workspaces

 

from there download the source files and build the project and use it directly to clean all these nasty folders

 

Tuesday, May 26, 2015

fatal error C1083: Cannot open precompiled header file: 'Debug\xxxxx.pch': No such file or directory

This error lost me a lot of time but fortunatly a wise guy at stackoverflow made an extensive explanation on how to solve it, the original thread is at this link :
how-to-fix-pch-file-missing-on-build

The whole problem lies in some header files needs to be already compiled so your compilation goes through. and there is some strategy for handling header files that must be precompiled as Jive Dadson explains in his answer :

  1. Right-click on your project in the Solution Explorer.
  2. Click Properties at the bottom of the drop-down menu.
  3. At the top left of the Properties Pages, select All Configurations from the drop-down menu.
  4. Open the C/C++ tree and select Precompiled Headers
  5. Precompiled Header: Select Use (/Yu)
  6. Fill in the Precompiled Header File field. Standard is stdafx.h
  7. Click Okay
  8. If you do not have stdafx.h in your Header Files put it there. Edit it to #include all the headers you want precompiled.
  9. Put a file named stdafx.cpp into your project. Put #include "stdafx.h" at the top of it, and nothing else.
  10. Right-click on stdafx.cpp in Solution Explorer. Select Properties and All configurations again as in step 4 ...
  11. ... but this time select Precompiled Header Create (/Yc). This will only bind to the one file stdafx.cpp.
  12. Put #include "stdafx.h" at the very top of all your source files. (Unix or cygwin users: find . -name "*.cpp" | xargs -n1 sed -i '1s/^/#include "stdafx.h"\n/')
Lucky 13. Cross your fingers and hit Build.


and this did all the magic for me :)

Tuesday, February 24, 2015

How to download all files recursively from HTTP folders:



Many times we are faced by the problem of downloading a folder listed by apache or IIS on the web, and we have to download the files one by one, or at best case go to each folder and download all links with a tool like downThemAll or FlashGot, which will download the files in a folder but not in sub folders.
a tip at this page :
https://bmwieczorek.wordpress.com/2008/10/01/wget-recursively-download-all-files-from-certain-directory-listed-by-apache/

shows how you can use a command line application named Wget to accomplish this.

Example: recursively download all the files that are in the ‘ddd’  folder for the url ‘http://hostname/aaa/bbb/ccc/ddd/;
Solution:
wget -r -np -nH –cut-dirs=3 -R index.html http://hostname/aaa/bbb/ccc/ddd/
Explanation:
It will download all files and subfolders in ddd directory:
recursively (-r),
not going to upper directories, like ccc/… (-np),
not saving files to hostname folder (-nH),
but to ddd by omitting first 3 folders aaa, bbb, ccc (–cut-dirs=3),
excluding index.html files (-R index.html)

In addition you may want to use a destination folder with the option
-P destDir
where destDir is your destination folder

you can download A GUI for this tool from here:
https://sites.google.com/site/visualwget/a-download-manager-gui-based-on-wget-for-windows

but actually the GUI tool didn't work for me and I ended using the wget.exe file used by this tool from the command line as explained above.