How to convert multiple tables into matrices

Hello Folks,
I'm trying to write a function, which converts every inputs as table in matrices. I used to use myTable{:,:} to do this for single input. Now it doesn't work anymore.

 Accepted Answer

For dealing with multiple tables, it is best to create a cell array
T = {myTable1, myTable2, myTable3};
Then you can function such as cellfun to create a cell array of matrices
M = cellfun(@(x) {x{:,:}}, T); % implicit for-loop
or create a single large matrix
M = [M{:}]; % connect horizontally
M = vertcat(M{:}); % connect vertically

8 Comments

Hi, many thanks for the quick answer. The number of tables is not given. It's like they give you a bunch of table. Use a single function to convert all of them into matrices and and then use matrix operation to solve the problem. I did the latter one and need a solution for the matrices
I'm newbie as well ...
Can you show an example of how the input tables are given, and what is your intended output?
must be like this: (table of n x n)
function [] = score(rawTable1,rawTable2)
% convert table into matrix
rawMatrix = rawTable1{:,:};
rawMatrix = rawTable2{:,:};
% then alot of matrix operations
end
now when I call the function, it should be like this:
score(table1,table2,table3,table 4...)
the function should convert them all in matrices and the output of these are a mean matrix, that includes the mean of every cells from each matrix
each time I run the function, the numbers of tables are different (is what I mean with ... in call function)
if the description does not clarify my problem, I can eventually post my code here if you have time for this. Thanks in advance
You can define a function like this
function [] = score(varargin)
rawMatrix = cellfun(@(x) {x{:,:}}, varargin);
% rawMatrix{1} is matrix for table1
% rawMatrix{2} is matrix for table2
% ..
% rawMatrix{end} is matrix for the last table
end
It accepts arbitrarily many tables. For example, call it like this
myTable1 = array2table(rand(5));
myTable2 = array2table(rand(5));
myTable3 = array2table(rand(5));
T = score(myTable1)
T = score(myTable1, myTable2)
T = score(myTable1, myTable2, myTable3)
All these calls are valid.
rawMatrix is a cell array. Following code shows how to take the mean of all matrices if all of them are of same dimensions
function y = score(varargin)
N = nargin; % number of tables
rawMatrix = cellfun(@(x) {x{:,:}}, varargin);
% rawMatrix{1} is matrix for table1
% rawMatrix{2} is matrix for table2
% ..
% rawMatrix{end} is matrix for the last table
y = mean(cat(3, rawMatrix{:}), 3);
end
Thank you. It works! You save my ass today.
I am glad to be of help! :)

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!