A better way to loop
이전 댓글 표시
I just finished a problem from a class in MatLab. In the problem statement we were given various arrays, the largest of which contained 5 elements and the shortest 2. So I went through with a lot of if loops with three conditional statements attached to each to try and help me understand exactly what the program was doing and when it was doing it. Anyway the maximum number of elements that my array calculation can do is 5. These arrays are suppose to serve as polynomial coefficients and return the coefficient number when the program is executed. I was thinking there has to be a way to make a program that could add a larger amount of elements from two arrays. Say 1000 or so in one and 500 in another. I was thinking maybe a for loop or a while loop but I'm not sure how I would do this. I originally tried a while loop in my code but got the machine stuck in an infinite loop. Clearly, I don't have the understanding of the language that I would like to have. I will include my code in this post but would like it if someone could explain how I may accomplish a task such as this if I had way more elements to add and if the arrays did not have the same dimensions.
p=input('values of p (remember to use brackets)\n');
s=input('values of s (remember to use brackets)\n');
P=fliplr(p);
S=fliplr(s);
[m,n]=size(P);
[a,b]=size(S);
if n~=b & n<b & n==1;
P=[P(1),0];
[m,n]=size(P);
end
if n~=b & n<b & n==2;
P=[P(1),P(2),0];
[m,n]=size(P);
end
if n~=b & n<b & n==3;
P=[P(1),P(2),P(3),0];
[m,n]=size(P);
end
if n~=b & n<b & n==4;
P=[P(1),P(2),P(3),P(4),0];
[m,n]=size(P);
end
if b~=n & b<n & b==1;
S=[S(1),0];
end
[a,b]=size(S);
if b~=n & b<n & b==2;
S=[S(1),S(2),0];
[a,b]=size(S);
end
if b~=n & b<n & b==3;
S=[S(1),S(2),S(3),0];
[a,b]=size(S);
end
if b~=n & b<n & b==4;
S=[S(1),S(2),S(3),S(4),0];
[a,b]=size(S);
end
Z=P+S;
h=fliplr(Z)
Any suggestions on the question would be greatly appreciated as well as suggestions on how I may improve the code I have posted. Thanks in advance.
댓글 수: 1
Jan
2012년 1월 26일
You are looking for a "better way to loop", but there is no loop in the code.
채택된 답변
추가 답변 (1개)
Oleg Komarov
2012년 1월 26일
If is a control flow statement not a loop.
Don't indent the if conditions if they are not nested.
if b~=n & b<n & b==1;
You can write the each sequence of |if|s as:
if b < n % which automatically excludes b == n
S = [S(1:n), 0]; % or P
[a,b] = size(s);
end
카테고리
도움말 센터 및 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!