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
Jan 2012 年 1 月 26 日
You are looking for a "better way to loop", but there is no loop in the code.

サインインしてコメントする。

 採用された回答

Jan
Jan 2012 年 1 月 26 日

0 投票

You do not need a bunch of IF-branchs:
if n < b
P = [P(1:n), 0];
n = n + 1;
%
S = [S(1:b), 0];
b = b + 1;
end
Is there really an exception at b==1? Your code looks a little bit confusing...

その他の回答 (1 件)

Oleg Komarov
Oleg Komarov 2012 年 1 月 26 日

0 投票

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 ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by