calling array entry based on variable

I have an array A and I want to call one of its entries. I want to predefine which entry by saying E='1,2' for example, and calling A(E). Is this possible?
EDIT:
I want to call A(1,2) but I want (1,2) to be defined before I call A(1,2)
So something like:
A=[1 2 3;4 5 6;7 8 9];
E='1,2';
A(E)
>>ans=2

답변 (1개)

Image Analyst
Image Analyst 2015년 4월 7일

0 개 추천

What does E mean? And what are its dimensions? If it's a 1x2 array that means a row and column, then you'd have to do A(E(1), E(2)).
If you simply did A(E) it would take that to mean you want two elements, A(E(1)) and A(E(2)), using E as linear indexes , not rows and columns. Since linear indexes go down the first column, then down the second column, etc. across all the columns, then A(E) would get A(1,1) and A(2,1). Just try it and see:
A=magic(4)
E = [1,2]
A(E)

댓글 수: 6

Josh's comment moved here:
I want to call A(1,2) but I want (1,2) to be defined before I call A(1,2)
So something like:
A=[1 2 3;4 5 6;7 8 9];
E='1,2';
A(E)
>>ans=2
James Tursa
James Tursa 2015년 4월 8일
편집: James Tursa 2015년 4월 8일
Josh: Assuming E is really a string, use IA's method but turn your string into indexes first. E.g.,
>> A=[1 2 3;4 5 6;7 8 9];
>> E = '1,2';
>> X = str2num(E)
X =
1 2
>> A(X(1),X(2))
ans =
2
Image Analyst
Image Analyst 2015년 4월 8일
Josh, that is even worse . Now you have E as a string instead of a numerical array. Why? Isn't "E" a variable that you create in your program? Why make it hard on yourself? Why make it an N by 2 array, or even worse, a string? Why not just keep track of the rows in a rows array and the columns in a columns array, then just do A(rows, columns) to get all of them, or A(rows(k), columns(k)) to extract out just the k'th row and column?
Josh
Josh 2015년 4월 8일
I have a grid of cells. There are several arrays with values at each of these cells. It is easier to refer to the cells by their location in space rather than the indices. So all the variables acting at location E will be A(E), B(E) etc
James Tursa
James Tursa 2015년 4월 8일
Josh: Is E a string or isn't it? If it is a string, then does it have to be a string or can you make it simpler on yourself as IA suggests?
Image Analyst
Image Analyst 2015년 4월 8일
Oh great - now they're cells? Or cell arrays? It's getting even worse. Plus you have several of these cell arrays, not just one, with possibly with different variable names (other than the badly-named "E"). What is the size of the cell arrays, and inside each cell, is there a numerical array, and what is the size of that array? I really urge you to simplify your programming life.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2015년 4월 7일

댓글:

2015년 4월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by