How to address a Matrix by not using the Indices?
Info
This question is closed. Reopen it to edit or answer.
Show older comments
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
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!