| External Interfaces/API | ![]() |
Passing Arrays of Strings
Passing arrays of strings involves a slight complication from the previous example in the Passing Strings section. Because MATLAB stores elements of a matrix by column instead of by row, it is essential that the size of the string array be correctly defined in the Fortran MEX-file. The key point is that the row and column sizes as defined in MATLAB must be reversed in the Fortran MEX-file. Consequently, when returning to MATLAB, the output matrix must be transposed.
This example places a string array/character matrix into MATLAB as output arguments rather than placing it directly into the workspace. Inside MATLAB, call this function by typing
passstr;
You will get the matrix mystring of size 5-by-15. There are some manipulations that need to be done here. The original string matrix is of the size 5-by-15. Because of the way MATLAB reads and orients elements in matrices, the size of the matrix must be defined as M=15 and N=5 from the MEX-file. After the matrix is put into MATLAB, the matrix must be transposed.
C $ Revision: 1.11 $
C==============================================================
C
C passstr.f
C Example for illustrating how to pass a character matrix
C from Fortran to MATLAB.
C
C Passes a string array/character matrix into MATLAB as
C output arguments rather than placing it directly into the
C workspace.
C
C This is a MEX-file for MATLAB.
C Copyright (c) 1984-2000 The MathWorks, Inc.
C==============================================================
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
C--------------------------------------------------------------
C (pointer) Replace integer by integer*8 on the DEC Alpha
C platform.
C
integer plhs(*), prhs(*)
integer p_str, mxCreateString
C--------------------------------------------------------------
C
integer nlhs, nrhs
integer i
character*75 thestring
character*15 string(5)
C Create the string to passed into MATLAB.
string(1) = 'MATLAB '
string(2) = 'The Scientific '
string(3) = 'Computing '
string(4) = 'Environment '
string(5) = ' by TMW, Inc.'
C Concatenate the set of 5 strings into a long string.
thestring = string(1)
do 10 i = 2, 6
thestring = thestring(:((i-1)*15)) // string(i)
10 continue
C Create the string matrix to be passed into MATLAB.
C Set the matrix size to be M=15 and N=5.
p_str = mxcreatestring(thestring)
call mxSetM(p_str, 15)
call mxSetN(p_str, 5)
C Transpose the resulting matrix in MATLAB.
call mexCallMATLAB(1, plhs, 1, p_str, 'transpose')
return
end
passstr
at the MATLAB prompt produces this result
ans = MATLAB The Scientific Computing Environment by TMW, Inc.
| Passing Strings | Passing Matrices | ![]() |