If-function in tables does not work

5 次查看(过去 30 天)
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

采纳的回答

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

请先登录,再进行评论。

更多回答(1 个)

Blue
Blue 2022-5-11
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)

类别

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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by