How do I design the structure and get the element according to its corresponding index?

1 次查看(过去 30 天)
I want to get the value of N and M after giving two index variable k and g, as shown in the figure. (k is a number and g is a string)
WeChat Image_20190128204601.jpg
For example:
k=get_k();
g=get_g();
if k == 1
N=92;
if g == 'cc'
M=300;
end
end
I tried to use cell to struct a "table",
where the first column is possible values of k,
the second column is the corresponding values of N,
and the third column is a cell contains information about g and its corresponding values of M:
Struct = {1,92,{'a',999;'cc',555;'de',44};...
2,61,{'a',666;'cc',33;'de',777};...
3,54,{'a',105;'cc',300;'de',46};...
6,106,{'a',55;'cc',666;'de',33};...
10,23,{'a',88;'cc',44;'de',111}}
I want to get the values of N and M using g and k.
My idea is to find the position of the k (i.e., row index of the first column in Struct) and then we can get the value of N.
Also, for the third column (i.e., the corresponding cell) in the same row, if we can find the position of g in that cell, we can get the value of M.
But I don't know how to get these two position.

采纳的回答

Munish Raj
Munish Raj 2019-2-8
编辑:Munish Raj 2019-2-8
I understand that you want to access the values of N, M using k, g as your indices.
You can exploit MATLAB’s logical indexing for this application.
The Structure definition is right on track for this purpose.
Assuming you have defined the structure in your question accurately, first column is k, second column is N, followed by a cell array with g, M.
The following code might be helpful
%Define your structure
Struct = {1,92,{'a',999;'cc',555;'de',44};...
2,61,{'a',666;'cc',33;'de',777};...
3,54,{'a',105;'cc',300;'de',46};...
6,106,{'a',55;'cc',666;'de',33};...
10,23,{'a',88;'cc',44;'de',111}}
%Structure is defined
%define the variables g and k
g=6;
k='a';
cellArray=Struct{cell2mat(Struct(:,1))==k,3}; %spotting the corresponding cell array
logicalCellArray=strcmp(cellArray,'de'); %converting the cellArray to a Logical table
M=y{logicalCellArray,2}; %obtaining the value of M
N=Struct{cell2mat(Struct(:,1))==k,2} %Obtaining the value of N
This can be consized to 2 lines of code, but this code if for your understanding of the algorithm.
Munish Raj

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by