A SUBSREF variant that accepts the 'end'-operator. - MATLAB Cody - MATLAB Central

Problem 2159. A SUBSREF variant that accepts the 'end'-operator.

Unfortunately, Matlab's subsref function does not support the end -operator. The end -operator is a powerfull method to refer to the rear-end of an array,

 a = 1:10;
 a(end-1) % is 9
 a(end-2:end) % is [8 9 10]

It works similar for cell arrays and struct-arrays.

Alhough subsref is quite powerful, and accepts for example the : colon oparator, it fails to process more complex stings, including end -operators.

This assignment is to create a function that accepts those more complex element definitions.

For example

 s.a.b(3).c{2}.d = 'a':'z';
 subsref(s,substruct('.','a','.','b','()',{3},'.','c','{}',{2},'.','d','()',{1:3})) 

returns

 ans = 
 abc  

And

subsrefbetter(s,substruct('.','a','.','b','()',{3},'.','c','{}',{2},'.','d','()',{'[1 end]'})) 

should return

 ans = 
 az  

and

subsrefbetter(s,substruct('.','a','.','b','()',{3},'.','c','{}',{2},'.','d','()',{'end-2:end'})) 

should return

 ans =
 xyz

The function subsrefbetter should accept both structures like created with substruct, and list of arguments like accepted by substruct.

That's all.

Solution Stats

35.71% Correct | 64.29% Incorrect
Last Solution submitted on May 03, 2025

Problem Comments

Solution Comments

Show comments
PIVlab surpasses 100K all-time File Exchange downloads
During the past twelve months, PIVlab, a MATLAB Community Toolbox for particle...
4
8

Problem Recent Solvers5

Suggested Problems

More from this Author31

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!