error: Matrix dimensions must agree

5 views (last 30 days)
Kalsoom Safdar
Kalsoom Safdar on 20 Aug 2023
Dear Researcher
I am getting error of dimision mismatch. The sample code is given below. Kindly help to remove the error.
Thanks
N=20;
D = 2;
l1b=-8283
u1b=-3422
lb = repmat(l1b,1,D);
ub = repmat(u1b,1,D);
nest =zeros(20, 10)
for i=1:N
for j=1:D
nestj(i,j) = lb(:,j) + nest.*(ub( :,j)-lb(:,j));
end
end
  1 Comment
Torsten
Torsten on 20 Aug 2023
I don't get what you want to do in the loop and how nestj should look like.

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 20 Aug 2023
nest is 20 by 20.
nest.* something is element-by-element multiplication, so if the multiplication worked at all, it would give a result that is at least 20 by 20. Adding something to that would still give a result that is at least 20 x 20. But you try to store that result into a scalar output location nestj(i,j)

Mrutyunjaya Hiremath
Mrutyunjaya Hiremath on 20 Aug 2023
Here, You're running a nested loop:
  • The outer loop (i) iterates over each trial or nest.
  • The inner loop (j) iterates over each dimension.
For each combination of trial and dimension:
  • lb(j) gets the lower bound for the specific dimension.
  • nest(i,j) accesses the value from the nest matrix for the current trial and dimension.
  • (ub(j) - lb(j)) computes the range or difference between the upper and lower bounds for the specific dimension.
  • The expression lb(j) + nest(i,j) * (ub(j) - lb(j)) scales the value in nest to fit within the range defined by lb and ub.
Finally, the code displays the nestj matrix, which contains the values of nest scaled to fit within the range specified by lb and ub.
N = 20;
D = 2;
l1b = -8283;
u1b = -3422;
lb = repmat(l1b, 1, D);
ub = repmat(u1b, 1, D);
nest = randi(100,[N, D]);
nestj = zeros(N, D);
for i = 1:N
for j = 1:D
nestj(i,j) = lb(j) + nest(i,j) * (ub(j) - lb(j));
end
end
disp(nestj)

Community Treasure Hunt

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

Start Hunting!