Code covered by the BSD License  

Highlights from
Straightforward COPY and PASTE functions

5.0

5.0 | 16 ratings Rate this file 41 Downloads (last 30 days) File Size: 5.51 KB File ID: #28016
image thumbnail

Straightforward COPY and PASTE functions

by

 

25 Jun 2010 (Updated )

Allows very simple manual exchange with other applications through the clipboard.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information
Description

Matlab's CLIPBOARD command allows the user to import and export data to and from other applications. But this command is limited to strings, or requires some mouse work when importing numerical arrays with the 'pastespecial' option.
This submission consists of two functions that make moving simple data from and to Matlab extremely easy. They are used as follows:
1) From Matlab to other application: In Matlab, say copy(x). Then in the other program (eg Excel, Word, Mathematica etc), import with the local Paste function. Depending on what kind of class x is, different material is pushed to the clipboard. For instance, if x is a numerical array, the receiving function will also see numerical data, not a string (as it would when using clipboard('copy',...)).
2) From another application to Matlab: In the other application, use the copy function to place content into the clipboard. Then, in Matlab, say x = paste; Depending of the structure of the data in the clipboard, the program makes x either a numerical array, a cell array, or a string.
See the help provided in the two functions for some examples. The two functions are limited to numerical arrays, cell arrays, and strings. They do not support structs or special classes.

Please comment if you like it or find it useful.

MATLAB release MATLAB 7.10 (R2010a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (34)
11 Nov 2014 Matthias Geissbuehler

A great addition to the Fileexchange!

Just a quick comment. I don't know why no one else faces the same troubles, but on my system (Matlab 2011a) the call:
test=paste;

fails with the following error:
---
??? Maximum recursion limit of 500 reached. Use
set(0,'RecursionLimit',N)
to change the limit. Be aware that exceeding your
available stack space can
crash MATLAB and/or your computer.

Error in ==> usejava
---

When I looked into the code with debug, I was able to identify it as the line 134:
p = clipboard('paste');
for some reason this line "calls" the "paste"-file again, leading to infinite recursion.
(although I don't know why clipboard calls a function instead of performing its "supposed" action)

Anyways: I solved the problem by simply changing the filename:
paste.m -> mypaste.m
copy.m -> mycopy.m

And in addition in "copy.m" you also need to change the line 111 to "mycopy".

After this it works like a charm. :-)

31 Mar 2014 Kyle  
18 Mar 2014 Yvan Lengwiler

Dear Soren. You are right. Thank you for finding this. I will update the file right now.

14 Mar 2014 Soren Preus

Excellent tool!

In copy, I believe line 129 should be:

strrep(mat2str(e),'.',dec)

instead of:

strrep(mat2str(e,'.',dec))

'dec' is also undefined within that same function which must be fixed in the input argument list and at line 92 and 94.

10 Mar 2014 Yvan Lengwiler

Thank you, Jiro, for finding this error. I've just uploaded a corrected version. In addition, it now also supports logical arrays.

10 Mar 2014 Jiro Doke

Hi Yvan,
Very nice entry! I think I may have found a bug. On line 205, I believe it should be

if numel(posComma) == 1 && numel(posPeriod) > 0

instead of

if numel(posComma == 1) && numel(posPeriod) > 0

20 Feb 2014 Chang hsiung  
20 Feb 2014 Yvan Lengwiler

Thank you Chang. I should have tested. I've just uploaded a small bugfix.

20 Feb 2014 Chang hsiung

>> copy([1:10])
Error: File: copy.m Line: 109 Column: 5
Illegal use of reserved keyword "else".

20 Feb 2014 Yvan Lengwiler

Great. I've just submitted the revision. Thank you for this improvement.

19 Feb 2014 Greg

Here is my suggestion:

xheaders = x.Properties.VariableNames;
xrownames = x.Properties.RowNames;
xdescr = {x.Properties.Description};
xt = table2cell(x);
if isempty(xrownames)
xrownames=repmat({''},height(x),1);
end
xt=[xdescr,xheaders;xrownames,xt];
if isempty(cat(2,xt{:,1}))
xt(:,1)=[];
end
copy(xt)

Most of the time, for me anyways, the description and row names are blank, and I wouldn't want it copying a blank first column, so that gets removed if they aren't there.

19 Feb 2014 Yvan Lengwiler

Greg, Thank you very much for this suggestion. 'table' seems to be a feature of R2013b, which I don't have. So I need some advice from you.

I can see, I believe, why you call 'copy' recursively (copy([xheaders;xt])). The reason is that [xheaders;xt] is a cell array.

But the table structure seems to accommodate rownames as well. Also, some other properties are available (such as a description). Would the following work?

xheaders = x.Properties.VariableNames;
xrownames = x.Properties.RowNames;
xdescr = x.Properties.Description;
xt = table2cell(x);
copy([xdescr,xheaders;xrownames,xt])

Maybe you could test this and let me know. If that works I will update the submission accordingly.

19 Feb 2014 Greg

Modified to support copying tables. Add the following lines within the main if/else.

% *** table ***************************
elseif isa(x,'table')
xheaders=x.Properties.VariableNames;
xt=table2cell(x);
copy([xheaders;xt])

23 Oct 2013 Laila h

I LOVE IT... THANK U SOOOO MUCH

27 Mar 2013 John D'Errico

Nice. useful. Well done.

27 Mar 2013 John D'Errico  
27 Mar 2013 arnold

ah well, no worries, thanks anyways.
It's very useful :)

26 Mar 2013 Yvan Lengwiler

Arnold. This seems to be a size constraint of the clipboard itself. Even the more basic attempt to put a 1024x1024 matrix into the clipboard, clipboard('copy',x), fails. So the problem is not in my copy function, but is deeper. I cannot address this, sorry.

24 Mar 2013 arnold

copying doesn't properly work though, can't copy a 1024x1024 double array to the clipboard
=====================================
>> copy(e,',');
Error using clipboard (line 63)
Java exception occurred:
java.lang.OutOfMemoryError: Java heap space

at
java.lang.AbstractStringBuilder.<init>(Unknown
Source)

at java.lang.StringBuffer.<init>(Unknown
Source)

at
sun.awt.datatransfer.DataTransferer.translateTransferable(Unknown
Source)

at
sun.awt.windows.WDataTransferer.translateTransferable(Unknown
Source)

at
sun.awt.windows.WClipboard.setContentsNative(Unknown
Source)

at
sun.awt.datatransfer.SunClipboard.setContents(Unknown
Source)

at
com.mathworks.page.utils.ClipboardHandler.copy(ClipboardHandler.java:70)

Error in copy (line 77)
clipboard('copy',s); % place
resulting string in clipboard

24 Mar 2013 arnold

thanks, well done!
There is one file here that apparently allows to copy/paste images:
http://www.mathworks.com/matlabcentral/fileexchange/14584-clipboardimage

19 Mar 2013 Yvan Lengwiler

Arnold, thank you for your suggestion. I have implemented three options now that allow you to handle non standard decimal separators, horizontal separators, and row separators.
Importing images is a completely different issue. A possible workaround is provided by the fact that an image is really just a three-dimensional matrix. However, these functions cannot handle such objects, so you would have to copy and paste the three colors of an RGB image separately. This is tedious, of course. Doing this more comfortably would be very convenient, but I guess this goes beyond these simple utilities. Or, maybe you have an idea how to do that?

19 Feb 2013 arnold

nice work, two remarks:

1. Switchable decimal separator
Some of us work in a windows environment that uses commas for separators (in Office i.e.). Maybe you could implement an option where one can easily switch between '.' and ',' as decimal separators. example:

==========================
test=ones(10)*0.1
copy(test,',')
==========================
this would copy the array to the clipboard with ',' as decimal separator. The standard option (copy(x)) should very well use points!

Example for paste. In Clipboard: '0,1'
==========================
x=paste(',')

--> x=0.1

y=paste;

--> y=1;
==========================

2. pasting Images
It would be great if you implemented pasting image-data, like a screenshot as an RGB Array.
This would be really cool, but I can't estimate how much work it'll cost, but then you'd definitely have owned your five stars ;)

03 Feb 2013 Yvan Lengwiler

Thank you, Hakan. This is a useful remark. I've uploaded a revision of the 'paste' function that tries to address this issue. It is, I believe, not possible to identify the formatting of the decimal and thousand separators with 100% accuracy (given an arbitrary string). The program will succeed if a comma is present in the number string.

So, both '1'234.56' and '1.234,56' will now be translated into the number 1234.56. Yet, '1.234' will always be interpreted as the number 1.234, even if 1234 was meant.

08 Jan 2013 hakan

Very usefull, but does not recognize "," as a decimal mark (which is default mark on excel).

22 Oct 2012 Rob  
04 May 2012 Joachim  
17 Feb 2012 Joe  
24 Jan 2012 Stefano

Thank you for these functions.
Very useful to overcome the limitations of the clipboard function.

25 Dec 2011 Yvan Lengwiler

Robert, thank you for your comment. I'm glad that the functions are helpful.

19 Dec 2011 Robert Alvarez

After fighting with Matlab's clipboard() function for an hour, I found these functions. They do what they're supposed to, no fuss, no bother. Thanks.

22 Jun 2011 Yvan Lengwiler

Thank you, Joseph. That's a valid point. I've addressed it (maybe slightly more elegantly) by catching this case in the 'onecell' subfunction.

function str = onecell(str,e,ch)
if isempty(e)
str = [str, ch];
elseif isa(e,'char') etc...

Update should be available soon.

22 Jun 2011 Joseph Burgel

Hi Yvan. Nice ftns. One thing I changed was to add special conditions for when a cell array has an 'empty' element. Rather that copying '[]', I test for empty and then simply add the tabs/CR. This way, Excel doesn't print anything for empties. Not sure if this will screw anything else up... In copy.m, line 51:

% *** cell argument **************************************************
elseif isa(x,'cell')
[nrow, ncol] = size(x);
str = '';
for r = 1:nrow
for c = 1:ncol-1
if isempty(x{r,c}),
str = [str char(9)];
else
str = onecell(str, x{r,c}, char(9)); % treat cell, append a tab
end
end
if isempty(x{r,end}),
str = [str char(10)];
else
str = onecell(str, x{r,end}, char(10));% treat cell, append a linefeed
end
clipboard('copy',str); % copy to clipboard
end
Thanks,

06 Jul 2010 Riccardo Meldolesi

Extremely useful. Well done

29 Jun 2010 Jonas Lundgren

Very useful! Tank you.

Updates
28 Jun 2010

Fixed a small bug in 'paste' and expanded help text.

10 Jul 2010

copy now also handles multi-line character arrays

05 Jun 2011

small improvemnt of efficiency

22 Jun 2011

Special treatment of empty cells (following a suggestion by Joseph Burgel).

04 Feb 2013

The paste function now tries to identify non-conventional decimal and thousand separators.

20 Mar 2013

Three new options are implemented, with allow the handling of unusually formatted numbers or separators (following a suggestion by arnold).

20 Feb 2014

Support for table variables (suggestion by Greg).

20 Feb 2014

small bug-fix

10 Mar 2014

Corrected a bug that Jiro Doke found (Thank you, Jiro). In addition, copy() now also supports logical arrays.

19 Mar 2014

bug fix

Contact us