problems with creating a multiplication table
显示 更早的评论
I want to make a function which creates a multiplication table with the dimensions C for Collumns and R for Rows. After creating the basic multiplication table the whole table has to be converted to a certain base b.
The code works as far as you use a method calls such as "multTable(7,3:10,2:3:33)". However i cant seem to find any good implementation that accepts method calls such as multTable(7,10,33). I tried checking to see if the R and C variable has zero, one or two ":" in them and then adding "1:" to the start of them but that didnt really work.
function y = multTable(b, R, C)
left = (R)';
top = (C);
table = (R)' * (C);
table = [left table];
top = [b top];
table = vertcat(top,table);
w = width(table);
h = height(table);
for i= 1:h
for ii = 1:w
a = dec2base(table(i,ii),b);
table(i,ii) = str2num(a);
end
end
table(1,1) = b;
y = table;
end
采纳的回答
更多回答(1 个)
If you change your code so as to no longer use table as a variable name (since table already has a meaning in MATLAB) you could build a multiplication table and store it as a table array.
x = 1:5;
n = numel(x);
t = table('Size', [n, n], ... % Preallocate t to be the correct size
'VariableTypes', repmat("string", 1, n), ... % All the elements will be strings
'RowNames', string(x), ... % Tables can have named rows
'VariableNames', string(x)) % and named variables (columns)
I'll fill in one element of the table.
t{4, 3} = 4*3
Let's extract that element back out.
twelve = t{"4", "3"}
And to show you the elements in the table can be different sizes:
t{5, 3} = string(dec2bin(5*3)) + "_b"
2 个评论
DGM
2022-8-11
I was kind of hoping someone would take this approach. It would improve readability over a cellchar. I just never use tables, so I'm reluctant to provide my own novice examples thereof. :)
One of the key points to remember when working with tables is how to store and access data inside them, and a key rule of thumb is that parentheses assign to or extract a sub-table while curly braces assign to or extract the contents of the sub-table. Those same rules of thumb apply to cell arrays: sub-cells (), contents {}.
t = array2table(magic(4))
subtable = t(1:2, 3:4)
numericArray = t{1:2, 3:4}
t(3:4, 1:2) = subtable
t{3:4, 3:4} = [999, 42; -1, Inf]
类别
在 帮助中心 和 File Exchange 中查找有关 Tables 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!