Matrix size mismatch Matlab Function

Hi,
I am trying to code this MATLAB Function where I am working with vectors:
function [Wp,S] = fcn(x, vel, Fext)
r=[Fext;x;vel];
p=50;
c=0.2;
mu=c*ones(1,p);
sigma=1;
alpha=0.01;
S=ones(p,1);
for j=1:p
S(j)=exp(-norm(r-mu(:,j))^2/(2*sigma^2));
end
Wp=alpha*Fext*S;
Wp=Wp';
I am getting this following error, but I don't get why there is a mismatch:
Size mismatch (size [1 x 1] ~= size [50 x 1]). The size to the left is the size of the left-hand side of the assignment.
Function 'MATLAB Function3' (#50.102.103), line 8, column 1: "S" Launch diagnostic report.
Thanks!

 Accepted Answer

Torsten
Torsten on 28 Mar 2023
Moved: Torsten on 28 Mar 2023
S(j) is a single value (1x1).
exp(-norm(r-mu(:,j))^2/(2*sigma^2)) is a vector (50x1).
You try to save a vector in a scalar value:
S(j)=exp(-norm(r-mu(:,j))^2/(2*sigma^2));
Error.

5 Comments

Hi Torsten! Thank you for your help!
I have changed it to:
S(j,1)=exp(-norm(r-mu(:,j))^2/(2*sigma^2));
And I am still getting the exact same error. Any other thoughts?
Thanks again!
Try
S(:,j)=exp(-norm(r-mu(:,j)).^2/(2*sigma^2));
It will at least work. I don't know if it's what you want.
Thanks again Torsten! Not sure why it's still giving me the same error... but I'll try to rewrite my code in a different way to try to avoid this notation. Thanks for your time!
How do you call the function (i.e. what is r) ?
This code works, e.g.:
x=1;
vel=1;
Fext = 1;
[Wp,S] = fcn(x, vel, Fext)
Wp = 1×50
0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038 0.0038
S = 50×1
0.3829 0.3829 0.3829 0.3829 0.3829 0.3829 0.3829 0.3829 0.3829 0.3829
function [Wp,S] = fcn(x, vel, Fext)
r=[Fext;x;vel];
p=50;
c=0.2;
mu=c*ones(size(r,1),p);
sigma=1;
alpha=0.01;
S=ones(p,1);
for j=1:p
S(j)=exp(-norm(r-mu(:,j))^2/(2*sigma^2));
end
Wp=alpha*Fext*S;
Wp=Wp';
end
Hey Torsten! Just made it work! So I am coding a Matlab function in Simulink, where it was giving me that error. So I moved to Matlab, and it does work fine there as you mentioned! So I realized that the issue was that in the Matlab function you have to specify the size of each variable, or it makes it "inherited". Anyways, thanks so much for yout help!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 28 Mar 2023

Commented:

on 28 Mar 2023

Community Treasure Hunt

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

Start Hunting!