conditions in matlab (for/if/else)

2 ビュー (過去 30 日間)
habib nasta
habib nasta 2018 年 10 月 7 日
コメント済み: Image Analyst 2018 年 10 月 7 日
Hi, I am trying to create a a function in which I can put in all the numbers from the 100 to 150 and extract all the odd numbers and do the sum square of these numbers I tried using the for function but I don't know how to take it after that

回答 (1 件)

Image Analyst
Image Analyst 2018 年 10 月 7 日
Try this:
% Generate starting signal.
v = 100:150
% Extract indexes of the odd numbers.
oddIndexes = logical(mod(v, 2))
% Extract the odd numbers themselves.
oddNumbers = v(oddIndexes)
% Compute the sum of the squares of odd numbers.
sumOfSuqares = sum(oddNumbers .^ 2)
Hopefully it's not your homework, or else you can't use my code.
  2 件のコメント
habib nasta
habib nasta 2018 年 10 月 7 日
thank you that was really helpful. It's not my homework actually (I wish it was) but i was wondering if you could show me how is it done using using the conditions like I was thinking that I should run a "for" from 100 to 150 and after that I should put a condition that if it's odd to store its square in a separate variable and after that sum it with the rest of the odd numbers but I am not sure how to tackle it honestly
Image Analyst
Image Analyst 2018 年 10 月 7 日
That's not the way MATLAB programmers would do it, unless they're a complete beginner coming from an old-school antique language. but nonetheless, here are both ways:
% Generate starting signal.
v = 100:150
% Klunky for loop way:
theSum = 0;
oddNumbers = []; % Initialize to null.
for k = 1 : length(v)
if rem(v(k), 2) == 1
% It's odd
oddNumbers = [oddNumbers, v(k)];
theSum = theSum + v(k)^2;
end
end
oddNumbers
theSum
% Much better vectorized way:
% Extract indexes of the odd numbers.
oddIndexes = logical(mod(v, 2))
% Extract the odd numbers themselves.
oddNumbers = v(oddIndexes)
% Compute the sum of the squares of odd numbers.
sumOfSuqares = sum(oddNumbers .^ 2)

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

カテゴリ

Help Center および File ExchangeDescriptive Statistics and Visualization についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by