How can I plot confidence intervals

15 views (last 30 days)
James Burrill
James Burrill on 29 Sep 2020
Answered: Raag on 9 May 2025
I am trying to plot confidence intervals but everytime I go to plot them it says that the matrix dimensions do not agree with the following error:
loglog(A(:,1),yCI50 + AllM)
Matrix dimensions must agree.
Here is my code
All(:,i) = A(:,2); %Extracts second column of data from each file
AllM = mean(All,2); %Takes mean of extracted data
loglog(A(:,1),AllM,'b') %Plots mean
S = size(All,2); %matrix length column 2 (ie. sample size)
ySEM = std(All)/sqrt(S); %Standard Error of the mean
CI50 = tinv([0.25 0.75], S-1); %T-score, 50% confidence int
yCI50 = bsxfun(@times, ySEM, CI50(:)); %calculates confideince interval
loglog(A(:,1),yCI50+AllM)
CI100 = tinv([0 1], S-1);
yCI100 = bsxfun(@times, ySEM, CI100(:));
loglog(A(:,1),yCI100+ALLM);

Answers (1)

Raag
Raag on 9 May 2025
Hi James,
As per my understanding, the issue you are facing arises from a matrix dimension mismatch when attempting to plot confidence intervals, specifically with the error “Matrix dimensions must agree”
This happens when you try to perform arithmetic (such as addition) on arrays of incompatible sizes. In the given code, the mean ‘AllM’ is a column vector, while the confidence interval matrix ‘yCI50’ is created as a 2 x N matrix, leading to the mismatch.
To resolve this, you need to ensure that the arrays you are adding have compatible dimensions. One of the ways to perform the same is to transpose the mean vector, so it matches the confidence interval matrix for plotting. Additionally, for clear visualization, I would recommend plotting the confidence interval as a shaded region (or error bars).
To resolve the issue, replace the portion of confidence interval calculation and plotting lines in the given code with the following:
% Calculate standard error of the mean (as a column vector)
ySEM = std(All,0,2) / sqrt(size(All,2)); % size: (number of data points x 1)
% Compute the 50% confidence interval bounds for each data point
CI50 = tinv([0.25 0.75], size(All,2)-1); % 1x2 vector
yCI50 = ySEM * CI50; % (number of data points x 2) matrix
% Plot the confidence interval as a shaded region
fill([A(:,1); flipud(A(:,1))], ...
[AllM + yCI50(:,2); flipud(AllM + yCI50(:,1))], ...
[0.8 0.8 1], 'EdgeColor', 'none', 'FaceAlpha', 0.3);
% Plot the mean again for clarity
loglog(A(:,1), AllM, 'b', 'LineWidth', 2);
This will result in the following output without any error:
For more information, you may find the following MATLAB documentation helpful:
2. plotting with confidence intervals: https://www.mathworks.com/help/matlab/ref/fill.html

Community Treasure Hunt

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

Start Hunting!