23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

6 Data Import and Export<br />

One <strong>MATLAB</strong> process (running send.m) writes a message to the file via its<br />

memory map. It also writes the length ofthemessagetobyte1inthefile,<br />

which serves as a means of notifying the other process that a message is<br />

available. The second process (running answer.m) monitors byte 1 and, upon<br />

seeing it set, displays the received message, puts it into uppercase, and echoes<br />

the message back to the sender.<br />

The send Function<br />

This function prompts you to enter a string and then, using memory-mapping,<br />

passes the string to another instance of <strong>MATLAB</strong> that is running the answer<br />

function.<br />

Copy the send and answer functions to files send.m and answer.m in your<br />

current working directory. Begin the demonstration by calling send with no<br />

inputs. Next, start a second <strong>MATLAB</strong> session on the same machine, and call<br />

the answer function in this session. To exit, press Enter.<br />

function send<br />

% Interactively send a message to ANSWER using memmapfile class.<br />

filename = fullfile(tempdir, 'talk_answer.dat');<br />

% Create the communications file if it is not already there.<br />

if ~exist(filename, 'file')<br />

[f, msg] = fopen(filename, 'wb');<br />

if f ~= -1<br />

fwrite(f, zeros(1,256), 'uint8');<br />

fclose(f);<br />

else<br />

error('<strong>MATLAB</strong>:demo:send:cannotOpenFile', ...<br />

'Cannot open file "%s": %s.', filename, msg);<br />

end<br />

end<br />

% Memory map the file.<br />

m = memmapfile(filename, 'Writable', true, 'Format', 'uint8');<br />

while true<br />

% Set first byte to zero, indicating a message is not<br />

6-70

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!