Use elements from 2d matrix as row number in a function
Mostrar comentarios más antiguos
Hello!!
I have a question about a function, I hope somebody could help me.
I have a 2d matrix --> MATR= (2160 rows, 4320 columns) --> MATR possible values: [1,2,3,4,5,6,7,8,9,10]
I have a function that must read the value in each MATR's cell, read numbers from a table where rows corresponds to MATR values, and assign new values to another 2d matrix.
EXAMPLE:
MATR(500,500)=7;
from row=7 of Table I read "18" --> new_MATR(500,500)=18.
All this must be done in a single step, avoiding loops or "if", for all the cells.
Thank you very much for your help
M
Respuestas (1)
If I understand correctly, you're describing a lookup table where you want to match the values in MATR with the values in column 1 of a table and return the values in column 2. If that's incorrect, please explain again.
Here's a demo.
% Create "fake" data for MATR and the lookup table T
MATR = randi(10,2160,4320);
T = table((1:10)', randi(20,10,1), 'VariableNames', {'A','B'});
% Match values from MATR to the first column of T (T.A)
% and return the values from the 2nd column (T.B).
[~, rowNum] = ismember(MATR, T.A);
MATR2 = T.B(rowNum);
4 comentarios
Matteo Rolle
el 2 de Mayo de 2020
Stephen23
el 2 de Mayo de 2020
Matteo Rolle's "Answer" moved here:
I'm sorry, it was exactly what I needed!! Thank you very much
I only have a problem with the last command (MATR2 = T.B(rowNum); )... this is the error message in the command:
Array indices must be positive integers or logical values.
Error in tabular/dotParenReference (line 108)
b = b(rowIndices);
Adam Danz
el 2 de Mayo de 2020
That means one of the values in MATR is not listed in T.A (variable names from my answer). The ismember function returns a 0 for the unmatched values and 0 cannot be used as a row index.
There are two ways to fix that. First, make sure T.A contains all possible vables in MATR. You could use the unique function to help you with that. Second, you could ignore the non-matches and return some default value such as NaN in their place.
[isMatch, rowNum] = ismember(MATR, T.A);
MATR2 = nan(size(MATR));
MATR2(isMatch) = rowNum(isMatch);
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!