Why do I keep getting this error? Error using surf Z must be a matrix, not a scalar or vector.

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)')
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.
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)')
Make sure you clear your variables. You probably have a variable the wrong size sitting around.

Sign in to comment.

Answers (2)

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

In particular. 1800 + j * h * 39 + j * g * 6 is a scalar result, so Mement(j/jinc, :) would be assigned only a single value.

Sign in to comment.

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

my assignment requires a nested loop. How would I do that?
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

Sign in to comment.

Categories

Find more on Graphics Performance in Help Center and File Exchange

Asked:

on 10 Apr 2023

Commented:

on 11 Apr 2023

Community Treasure Hunt

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

Start Hunting!