Anton Daneyko
Anton Daneyko

Reputation: 6503

In Matlab, can I access an element of an array, which is in turn a value of a container.Map?

Here is a code snippet, that shows what I want and the error, that follows:

a = [1, 2];
m = containers.Map('KeyType','char', 'ValueType','any');
m('stackoverflow.com') = a;
pull_the_first_element_of_the_stored_array = m('stackoverflow.com')(1);
??? Error: ()-indexing must appear last in an index expression.

How do I access an element of the array, which is in turn a value of a map object? I could have done this:

temp = m('stackoverflow.com');
pull_the_first_element_of_the_stored_array = temp(1);

But I do not want to create an intermediate array only to pull a single value out of it.

EDIT : This is a duplicate of How can I index a MATLAB array returned by a function without first assigning it to a local variable? The answer is there.

Upvotes: 5

Views: 2120

Answers (2)

gnovice
gnovice

Reputation: 125864

Although this question is a duplicate of this previous question, I feel compelled to point out one small difference between the problems they are addressing, and how my previous answer could be adapted slightly...

The previous question dealt with how to get around the syntax issue involved in having a function call immediately followed by an indexing operation on the same line. This question instead deals with two indexing operations immediately following one another on the same line. The two solutions from my other answer (using SUBSREF or a helper function) also apply, but there is actually an alternative way to use SUBSREF that combines the two indexing operations, like so:

value = subsref(m,struct('type','()','subs',{'stackoverflow.com',{1}}));

Note how the sequential index subscripts 'stackoverflow.com' and 1 are combined into a cell array to create a 1-by-2 structure array to pass to SUBSREF. It's still an ugly one-liner, and I would still advocate using the temporary variable solution for the sake of readability.

Upvotes: 1

Pursuit
Pursuit

Reputation: 12345

This is another case where you can get around syntax limitations with small helper functions. EG:

getFirst = @(x)x(1);

pull_the_first_element_of_the_stored_array = getFirst(m('stackoverflow.com'));

This still needs two lines, but you can often reuse the function definition. More generally, you could write:

getNth = @(x, n) x(n);

And then use:

getNth (m('stackoverflow.com'),1);

Upvotes: 6

Related Questions