If-function in tables does not work

5 Ansichten (letzte 30 Tage)
Tobias Kleinert
Tobias Kleinert am 11 Mai 2022
Kommentiert: Tobias Kleinert am 12 Mai 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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 11 Mai 2022
if Tab{TabLength,numb1} == 5
  1 Kommentar
Tobias Kleinert
Tobias Kleinert am 12 Mai 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Blue
Blue am 11 Mai 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)

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by