Michael A
Michael A

Reputation: 4615

How do I use MATLAB's substruct function to create a struct representing a reference that uses "end"?

I'd like to use the substruct function to create a structure for use in subsref. The purpose is to index a string using subsref instead of the usual ( ) notation because I'm subscripting the output of a function. This is a simple example of what I'm trying to do (in my actual code, this is used within a cellfun, so the strings can be of different lengths and the replacement isn't always in the same place):

data = 'quick brown fox';
data2 = strrep(data, 'brown', 'green');
data2(7:end)

Heres where I tried to define this subscripting with substruct:

data = 'quick brown fox';
S = substruct('()', {[7:end]});
subsref(strrep(data, 'brown', 'green'), S)

but this just gives me an error:

Error using substruct (line 30)
SUBSTRUCT takes at least two arguments.

Error in myfile (line 3)
S = substruct('()', {(7:end)});

I've been over and over the documentation for both substruct and subsref, and no where do they mention end. How do I do this?

Upvotes: 4

Views: 619

Answers (1)

Oleg
Oleg

Reputation: 10676

There is no way to my knowledge to do that with subsref which assumes you know exactly which subs you will need.

Use @function_handle to dynamically determine the end:

f = @(x) x(7:end);
f(strrep(data, 'brown', ''))
ans =
  fox

Upvotes: 1

Related Questions