Questions about how to plot a summation function with two variables

Hello, I am trying to plot a summation function with two variables (x and y) shown in the figure. My code is:
[x,y] = meshgrid(1:1:40,1:1:5);
z=fun(x,y);
surf(x,y,z);
function [z] = fun(x,y)
z=0;
for i=1:x
z=z+(0.5.^((i-1)./x)-0.5.^(i./x)).*(1-(exp(y)-1)./(exp(y).*0.5.^(i./x)-0.5.^((i-1)./x)));
end
end
But the results are only valid for i=1, not for i=1:x. I can not find the errors, so I need help from all of you. Thanks in advance.

 채택된 답변

James Tursa
James Tursa 2020년 12월 21일
편집: James Tursa 2020년 12월 21일
From the formula image, it appears you need fun( ) to create a matrix z where each element corresponds to the formula for a particular x and y pair. E.g., since you are passing in matrices
function z = fun(X,Y)
z = zeros(size(X));
for x = X
for y = Y
% insert your for-loop here to update z(x,y)
end
end

댓글 수: 6

I was just typing up something similar, so I'll just append this thought here.
@Yao Zhao, if you look at your function, you have x, which is a 5x40 matrix. You write a for loop that
for i = 1:x
end
but what does that mean? What does it mean for i to vary from [1] to [5x40 matrix]?
James and I are making the same point: You need to deal with the matrix nature of x and y.
Hi, James and cyclist, thanks for your replies. I realize the error has something to do with the x in "i=1:x". I misunderstood x was a scalar and wanted i to increase from 1 to x. This is to say, I wish to have the summation of values from i=1 to i=x. Here, x is a variable and changes from 1 to 40. This question is a little complicated for me. I tried James's method, but it still not work.
What have you tried? Basically all you needed to do was use the code I posted and insert your for-loop using z(x,y) instead of z.
[X,Y] = meshgrid(1:1:40,1:1:5);
z=fun(X,Y);
surf(X,Y,z);
function z = fun(X,Y)
z = zeros(size(X));
for x=X
for y=Y
for i=1:x
z(x,y)=z+(0.5.^((i-1)./x)-0.5.^(i./x)).*(1-(exp(y)-1)./(exp(y).*0.5.^(i./x)-0.5.^((i-1)./x)));
end
end
end
end
I tried this one. It says "Unable to perform assignment because the size of the left side is 5-by-5 and the size of the right side is 5-by-40."
Sorry. I forgot how for-loops act on matrices used for indexing (they do it by entire columns at once). Try this instead:
for m = 1:size(z,1)
for n = 1:size(z,2)
x = X(m,n);
y = Y(m,n);
for i=1:x
z(m,n) = z(m,n) + etc.
Thank you very much, James. This problem is solved!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Graphics Performance에 대해 자세히 알아보기

질문:

2020년 12월 21일

댓글:

2020년 12월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by