Code covered by the BSD License  

Highlights from
subarray

Be the first to rate this file! 3 Downloads (last 30 days) File Size: 1.46 KB File ID: #24457

subarray

by Peter Mao

 

16 Jun 2009 (Updated 01 Aug 2011)

Extracts a subarray from an array. Useful for function outputs.

| Watch this File

File Information
Description

extracting a subarray from an array is simple:

a = 1:10;
a(4:8) %returns elements 4-8.

but sometimes, I have a function that returns an array, but I only want a subset of that array:

a = foo(x,y,z);
b = a(2,9:end);

Here 'a' is a temporary variable, polluting my workspace. Hence subarray:

b = subarray(foo(x,y,z),2,'9:end');

SUBARRAY should handle all the normal indexing cases (output of FIND, ranges, unspecified dimensions) just like the first example. The only exception is the 'end' keyword, where we have to pass in a string and EVAL it.

I tip my hat to Garret Euler of SUBMAT and SUBMAT_NOEVAL.

Acknowledgements

The author wishes to acknowledge the following in the creation of this submission:
submat, submat_noeval

MATLAB release MATLAB 7.8 (R2009a)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (3)
17 Jun 2009 Matt Fig

You could also do this:

a = foo(x,y,z);
a = a(2,9:end);

Then there is no temporary variable polluting your workspace.

09 Jun 2011 Peter Mao

I've noticed recently that using ":" in scripts works fine, but in a function, the call to subarray gets evaluated as the unknown variable "subarray"

Haven't got a solution for that yet.

03 Aug 2011 Oleg Komarov

You don't have to eval it:

a = 1:10;
a(':')

The other case '9:end' could be handled w/o eval.

Please login to add a comment or rating.
Updates
01 Aug 2011

prev version wasn't handling 1xn matrices in the expected way (it wasn't skipping the singeton dimensions). usage in functions seems to be well behaved now, provided one uses quotes around :'s and "end"'s

Tag Activity for this File
Tag Applied By Date/Time
array Peter Mao 17 Jun 2009 13:49:14
array manipulation Peter Mao 17 Jun 2009 13:49:14
matrix Peter Mao 17 Jun 2009 13:49:14
subarray Peter Mao 17 Jun 2009 13:49:14
submatrix Peter Mao 17 Jun 2009 13:49:14
subset Peter Mao 17 Jun 2009 13:49:14

Contact us at files@mathworks.com