How to address a Matrix by not using the Indices?

Hello everybody, I have a problem. I initialized a Matrix with two dimensions. One dimension stands for the age 0-100 and one for the generation 1900-2000. I filled the Matrix with some numbers so that we have a 101 x 101 Matrix. To get the number for age 20 of generation 1950 I access the Matrix by
Matrix(21,51)
What I would love to do it the obvious way:
Matrix(20,1950)
But that of course would exeed the dimension of the Matrix. I could write a method/function to convert the indices like
function Out=GetNumber(Age,Gen)
Out=Matrix(Age+1,Gen-1900+1);
end
but then can't use the colon Operator anymore. Does anybody has an idea how to Bypass that Problem?

Answers (1)

First some trial data:
>> M = [1,2,3;4,5,6;7,8,9] % data
M =
1 2 3
4 5 6
7 8 9
>> rV = [20,21,22]; % rows
>> cV = [1950,1951,1952]; % columns
Solution 1
One function that accesses the matrix directly:
>> fun = @(r,c)M(ismember(rV,r),ismember(cV,c));
>> fun(21,1950:1951)
ans =
4 5
Solution 2
Two indexing functions:
>> rI = @(r)ismember(rV,r);
>> cI = @(c)ismember(cV,c);
and trying it out:
>> M(rI(21),cI(1950:1951))
ans =
4 5
Solution 3
Or perhaps you could get a table to do what you need.

3 Comments

Thank you for the quick reply, but both solutions don't work with just the colon operator to get the entire row:
>> fun(21,:)
Input arguments to function include colon operator. To input the colon character, use ':' instead.
Or
>> M(rI(21),cI(:))
Input arguments to function include colon operator. To input the colon character, use ':' instead.
What you wanting amounts to indexing with an arbitrary starting index (MATLAB indexing starts at one). Like most languages, in MATLAB the starting index cannot be changed arbitrarily.
There is no easy solution that will fit your requirements.
There is a solution that would fit the requirement, that would involve writing a custom class and overriding the subsref (and subsasgn) operator.
It probably would be more work than it's worth.

This question is closed.

Asked:

on 4 Feb 2016

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!