フィルターのクリア

Proper Syntax for a Nested Loop

1 回表示 (過去 30 日間)
Frank Lehmann
Frank Lehmann 2023 年 8 月 7 日
コメント済み: Matt J 2023 年 8 月 7 日
Hi All,
Im having issues with following code where I believe I may need an additional nested loop.Basically I want the first 2 rows for the 2nd column to reduce by 1 and rows 3 onwards to stay the same value as columns 2. The result Im getting is [ 74 15 12 33] the first 2 elements are correct but the last two should read [24 44], the final result I wish [ 74 15 24 44] I know I need to insert an additional loop somwhere could anyone guide me or provide have a simpler solution on how to reduce column 2 from 1 to 0 from rows 3 onwards?
motData=[12,2;37,3;11,4;15,2];
motData=sortrows(motData,'descend')
i=zeros(size(motData));
p=size(motData,1)
for t =1:p
newmodVector1(t)=(motData(t,1).*(motData(t,2)-1))
end
Thanks,
Frank

採用された回答

Voss
Voss 2023 年 8 月 7 日
編集済み: Voss 2023 年 8 月 7 日

No additional loop is necessary.

You can replace your existing loop with this one:

for t =1:p
    newmodVector1(t)=motData(t,1).*(motData(t,2)-(t<=2));
end

Or you can do it without a loop at all:

newmodVector1=(motData(:,1).*(motData(:,2)-((1:p).'<=2))).';

Omit the final transpose (.') if you want newmodVector1 to be a column vector.

  2 件のコメント
Frank Lehmann
Frank Lehmann 2023 年 8 月 7 日
Thanks Voss much appreciated!!
Matt J
Matt J 2023 年 8 月 7 日
@Frank Lehmann Since Voss provided a valid solution for you should should Accept-click the answer. It would also be good if you went back to do the same with your previous posts.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by