Why do I keep getting this error? Error using surf Z must be a matrix, not a scalar or vector.
Show older comments
Moment=zeros(); ki=pi/180; kinc=pi/180; kf=pi; ji=5; jinc=5; jf=100;
for k=ki:kinc:kf
for j=ji:jinc:jf
h=sin(k)
g= cos(k)
Moment (j/jinc,:) = 1800 + j * h * 39 + j * g * 6
end
end
%k is theta j is force
[k,j] = meshgrid(ki:kinc:kf,ji:jinc:jf);
figure
surf(k,j,Moment)
xlabel('0 (degrees)'); ylabel('Force (lbs)'); zlabel('Moment (lbs-ft)')
10 Comments
one way to modify your code is below
ki=pi/180; kinc=pi/180; kf=pi; ji=5; jinc=5; jf=100;
Moment=zeros();
% initialize a counter
K = 1;
for k=ki:kinc:kf
for j=ji:jinc:jf
h(K) = sin(k); % make h as array
g(K) = cos(k); % make g as array
Moment (j/jinc,1:K) = 1800 + (j) * h * 39 + (j) * g * 6;
end
K = K+1; % increment in for loop
end
% plot using surf
[k,j] = meshgrid(ki:kinc:kf,ji:jinc:jf);
figure
surf(k,j,Moment)
xlabel('0 (degrees)'); ylabel('Force (lbs)'); zlabel('Moment (lbs-ft)')
MyRanda
on 11 Apr 2023
Walter Roberson
on 11 Apr 2023
K=1;
so 1:K is 1:1 so you are assigning to Moment(something, 1) which is creating a vector, not a 2D array.
MyRanda
on 11 Apr 2023
Walter Roberson
on 11 Apr 2023
Your posted code is running.
MyRanda
on 11 Apr 2023
Walter Roberson
on 11 Apr 2023
Make sure you clear your variables. You probably have a variable the wrong size sitting around.
Adam Danz
on 11 Apr 2023
Note, duplicate
Answers (2)
Cris LaPierre
on 11 Apr 2023
0 votes
Because your variable moment is a vector not a matrix. moment must be the same size as k and j (the ones resulting from your meshgrid operation).
1 Comment
Walter Roberson
on 11 Apr 2023
In particular. 1800 + j * h * 39 + j * g * 6 is a scalar result, so Mement(j/jinc, :) would be assigned only a single value.
Walter Roberson
on 11 Apr 2023
Moved: Walter Roberson
on 11 Apr 2023
ki=pi/180; kinc=pi/180; kf=pi; ji=5; jinc=5; jf=100;
[k,j] = meshgrid(ki:kinc:kf,ji:jinc:jf);
h = sin(k);
g = cos(k);
Moment = 1800 + j .* h .* 39 + j .* g .* 6;
surf(k, j, Moment);
xlabel('0 (degrees)'); ylabel('Force (lbs)'); zlabel('Moment (lbs-ft)')
2 Comments
MyRanda
on 11 Apr 2023
Walter Roberson
on 11 Apr 2023
Do the meshgrid first. Then
for ridx = 1 : number of rows
for cidx = 1 : number of columns
output_variable(ridx,cidx) = calculation in terms of variables indexed at (ridx,cidx);
end
end
Categories
Find more on Graphics Performance 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!

