Borrar filtros
Borrar filtros

Acessing fields of a structure

1 visualización (últimos 30 días)
José Pereira
José Pereira el 7 de Dic. de 2017
Editada: James Tursa el 7 de Dic. de 2017
Hi I have a structure called 'users' with 2 fields: username and password. If i know the username how can i have access to the corresponding password?

Respuestas (2)

Star Strider
Star Strider el 7 de Dic. de 2017
I would use the strcmp function for the name comparison:
users.username = {'Name_1', 'Name_2'}; % Create Structure
users.password = {'password_1', 'password_2'}; % Create Structure
Lidx = strcmp(users.username, 'Name_2'); % Return ‘Logical Index’
PW = users.password(Lidx)
PW =
1×1 cell array
{'password_2'}

James Tursa
James Tursa el 7 de Dic. de 2017
Editada: James Tursa el 7 de Dic. de 2017
Assuming your struct is multi-element, with each element having a username and a password. One way, which first converts the username fields into a cell array that can be fed into strcmp:
username = whatever;
password = users(strcmp({users.username},username)).password;
This assumes that username is actually present in the struct exactly once. If that may not be the case, then you would need to add in logic to test the result of the strcmp first.
This also converts the username fields to a cell array first. That carries a performance penalty. If you were doing this for many user names using the same struct, then consider doing that conversion only once at the front instead of multiple times.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by