error: Matrix dimensions must agree / Inner matrix dimensions must agree.

1 view (last 30 days)
Hi, I tried to multiply two different matrix but program give me an error which is "Inner matrix dimensions must agree". here is my code:
Schedule=[1,4,3,1,1];
nstands=5;
nperiods=4;
adjacency = [0, 1, 1, 0, 1;
1, 0, 0, 1, 0;
1, 0, 0, 0, 0;
0, 1, 0, 0, 0;
1, 0, 0, 0, 0];
adj = tril(adjacency)
n=max(Schedule);
out=zeros(n);
for k=1:n
idx=find(Schedule==k);
out(k,idx)=1;
end
ady = sum((out * adj)') % Error using * Inner matrix dimensions must agree.
totaladdy = sum(ady)
i tried to change it with " .* " but this time it gives : "Matrix dimensions must agree"
This code works when i use on commond window or scipts without other code. whenever i add into the main code it gives an error. I tired to create function and call it in the main code as well. like this
function [ totaladdy ] = calcaddy( schedule, adjacency )
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
adj = tril(adjacency);
n=max(schedule);
out=zeros(n);
for k=1:n
idx=find(schedule==k);
out(k,idx)=1;
end
ady = sum((out * adj)');
totaladdy = sum(ady);
end
in the main code i call function like this
[ totaladdy ] = calcaddy( breedingpopulation, adjacency );
Thank you

Answers (1)

Walter Roberson
Walter Roberson on 3 Sep 2013
Your adjacency matrix is 5 x 5. tril() of a 5 x 5 is 5 x 5.
Your Schedule has a maximum of 4, so "n" is 4. zeros(n) would be zeros(4) which would be 4 x 4.
You try to do a matrix multiplication of (5 x 5) x (4 x 4) . The second dimension of the first array, 5, does not match the first dimension of the second array, 4, so you cannot matrix multiply the two.
I would suggest
out = zeros(size(adjacency));
but leave n as max(Schedule)

Categories

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

Community Treasure Hunt

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

Start Hunting!