If-function in tables does not work

5 visualizaciones (últimos 30 días)
Tobias Kleinert
Tobias Kleinert el 11 de Mayo de 2022
Comentada: Tobias Kleinert el 12 de Mayo de 2022
Dear community,
I am trying to solve an apparently simple problem for days now (code below), but I just can't find a solution...
I created a table (Tab) that contains two columns with numbers (numb1 & numb2, in the original it also contains strings). I want to create a new file (answer) in the same format, which contains two columns with zeros, but a one in case of the number 5 (i.e., for numb1: 0,0,0,0,1,0,0 & for numb2: 0,0,1,0,0,0,0). I tried to solve this with an 'if' function, but I get an error message that the usage of '=' is not supported for tables. The original 'struct' format didn't work either, neither did it work for cells... Please help!!
numb1 = [1;2;3;4;5;6;7];
numb2 = [7;6;5;4;3;2;1];
Tab = table(numb1, numb2)
for TabLength = 1:height(Tab)
if Tab(TabLength,numb1) == 5
answer(TabLength,1) = 0
else
answer(TabLength,1) = 1
end
end
xxx

Respuesta aceptada

Walter Roberson
Walter Roberson el 11 de Mayo de 2022
if Tab{TabLength,numb1} == 5
  1 comentario
Tobias Kleinert
Tobias Kleinert el 12 de Mayo de 2022
HALLELUJAH! The correct code should be if Tab{TabLength,1} == 5
Simply incredible how simple of a solution can require such a long time.
Thank you sir. Made my day

Iniciar sesión para comentar.

Más respuestas (1)

Blue
Blue el 11 de Mayo de 2022
If I understand correctly, the cyclist has answered this question: https://www.mathworks.com/matlabcentral/answers/321819-how-to-find-index-of-a-value-in-cell-array
numb1 = {1;2;3;'A';5;6;7};
numb2 = {7;'D';5;4;3;2;1};
Tab = table(numb1, numb2)
ans1 = double(cellfun(@(x)isequal(x, 5), Tab.numb1));
ans2 = double(cellfun(@(x)isequal(x, 5), Tab.numb2));
answer = table(ans1, ans2)

Categorías

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

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by