how to do correlation tests to a cell array

4 views (last 30 days)
Hugo
Hugo on 24 Feb 2022
Answered: Arjun on 10 Oct 2024
Hi,
I have a cell array with 24 cells. I am trying to write a correlation between the variables inside each cell. In each cell, there is a table with dimensions 20*20. How can I write efficiently a code to automate it? Right now, my for cycle returns me an error, so I am sure something must be changed/added.
for i=1:1:24
figure;
set(gcf,"Visible","on");
correlationP1= corr(mydada{1, i},"rows","pairwise","type","Pearson")
end
I thank you in advance,
Best regards

Answers (1)

Arjun
Arjun on 10 Oct 2024
Hi @Hugo,
I see that there is a cell array in which each entry is a 20x20 table and you want to do correlation test on these tables.
The “corr” function in MATLAB expects inputs to be matrices but, in the code, provided, a table is passed as an input argument to the “corr” function which might be the cause of the error you are facing. It is suggested to use “table2array” function of MATLAB to convert the table to array and then pass it to the “corr” function.
Please refer to the code below for better understanding:
% creating some random data in the same format
mydata = cell(1, 24);
for i = 1:24
randomData = rand(20, 20);
mydata{1, i} = array2table(randomData);
end
% calculation of correlation matrix
for i = 1:24
currentTable = mydata{1, i};
% Calculate the correlation matrix
correlationP1 = corr(table2array(currentTable), 'rows', 'pairwise', 'type', 'Pearson');
% Display the correlation matrix as per need
figure;
imagesc(correlationP1);
colorbar;
title(['Correlation Matrix for Cell ', num2str(i)]);
xlabel('Variable Index');
ylabel('Variable Index');
set(gcf, 'Visible', 'on');
end
Kindly go through the documentation of “corr” and “table2array” function for better understanding:
I hope this will help!

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Tags

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!