Alternative for linspace?
조회 수: 76 (최근 30일)
이전 댓글 표시
function [xvals, yvals]=A5fourier(L,nmax,numpoints)
%xvals=linspace(-L,L,numpoints);
for z=-0.1:0.001:0.1
xvals=z;
end
yvals=zeros(1,numpoints);
for i=1:numpoints
for j=1:2:nmax
yvals(i)=(4/pi)*(yvals(i)+(1/j)*sin(j*pi*xvals(i)/L));
j=j+1;
end
i=i+1;
end
L in this function is 0.1, and numpoints is 200. I've been challenged to use a loop rather than linspace to create the same 200 equally spaced points. My current solution ruins my yvals part of the function returning an error "Index exceeds the number of array elements". How can I remedy linspace while mainting the rest of my function?
댓글 수: 0
답변 (1개)
DGM
2022년 2월 11일
편집: DGM
2022년 2월 11일
Why not just use the colon operator?
r = [-4 4];
n = 10;
x1 = linspace(r(1),r(2),n)
x2 = r(1):range(r)/(n-1):r(2)
This can definitely be simplified. The iterator in a for-loop doesn't need to be incremented.
yvals=zeros(1,numpoints);
for i=1:numpoints
for j=1:2:nmax
yvals(i)=(4/pi)*(yvals(i)+(1/j)*sin(j*pi*xvals(i)/L));
% j=j+1; % this doesn't do anything
end
% i=i+1; % this doesn't do anything
end
댓글 수: 1
VBBV
2024년 2월 25일
@Sarah Gomez, if your question involves, to use the for loops /other loops to create linearly spaced points, then this could be one option to do so, however, there are several redundant lines of code in your function whcih @DGM pointed out. Further, ihe simplest altrenative would be to use the colon : operator which also was mentioned by @DGM
[xvals yvals] = A5fourier(0.1,200,200)
linspace(-0.1,0.1,200)
function [xvals, yvals]=A5fourier(L,nmax,numpoints)
%xvals=linspace(-L,L,numpoints);
% alternative to linspace using for loops !!!
k = 1;
for z=-0.1:0.001:0.1
xvals(k)=z;
k = k+1;
end
yvals=zeros(1,numpoints);
for i=1:numpoints
for j=1:2:nmax
yvals(i)=(4/pi)*(yvals(i)+(1/j)*sin(j*pi*xvals(i)/L));
end
end
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!