I have been asked to create the following:
Create a function called Ex7b with 2 inputs (n and m) and a single output. Write the function so the output is the sum of the sets of n numbers between 1 and m. for example if n=4 and m=100:
?????? = [1 + 2 + 3 + 4 5 + 6 + 8 + 9......97 + 98 + 99 + 100]. The function should round m to the nearest multiple of n.
I have looked at all the info on creating functions, but have no idea on where to start with this one.
Thanks

 ์ฑ„ํƒ๋œ ๋‹ต๋ณ€

Stephan
Stephan 2019๋…„ 3์›” 1์ผ

0 ๊ฐœ ์ถ”์ฒœ

Hi,
start reading here and work through the examples given:
Best regards
Stephan

๋Œ“๊ธ€ ์ˆ˜: 4

Sam Thorpe
Sam Thorpe 2019๋…„ 3์›” 1์ผ
Hi Stephan,
I understand the underlying concepts around creating functions, what I'm struggling with here is seperating the values in the array so I can add them together.
I have tried specifying output as 1:n:m as to start at 1 and count up in values of n until it reached the mth term, but this just skips every nth value and returns the sum of the lot.
Stephan
Stephan 2019๋…„ 3์›” 1์ผ
Try to understand what happens:
m = 100
n = 4
result = sum(reshape(1:m,n,[]),1)
Therefore:
  • think about what 1:m does
  • read about reshape --> reshape(x,m,n)
  • and check how this sum works - meant is input argument '1' --> sum(x,1)
Sam Thorpe
Sam Thorpe 2019๋…„ 3์›” 4์ผ
Thank you for your help Stephan. After a bit of logical thinking and your tips, I have gotten the function to work exactly as I wanted.
function ex7b=sumset(n,m)
o=n*ceil(m/n) %round the array up to nearest multiplication of n
p=[1:o] %definition of the array
q=(numel(p))/n %calculation of column size
x=reshape(p,[n,q]) %reshaping the array in to an n by m/n array
y=x.' %transposition of array
z=sum(y) %sum of each array row
end
Stephan
Stephan 2019๋…„ 3์›” 4์ผ
Nice to hear

๋Œ“๊ธ€์„ ๋‹ฌ๋ ค๋ฉด ๋กœ๊ทธ์ธํ•˜์‹ญ์‹œ์˜ค.

์ถ”๊ฐ€ ๋‹ต๋ณ€ (0๊ฐœ)

์นดํ…Œ๊ณ ๋ฆฌ

๋„์›€๋ง ์„ผํ„ฐ ๋ฐ File Exchange์—์„œ Data Type Conversion์— ๋Œ€ํ•ด ์ž์„ธํžˆ ์•Œ์•„๋ณด๊ธฐ

ํƒœ๊ทธ

์งˆ๋ฌธ:

2019๋…„ 3์›” 1์ผ

๋Œ“๊ธ€:

2019๋…„ 3์›” 4์ผ

Community Treasure Hunt

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

Start Hunting!

Translated by