Using diff() in a for loop

조회 수: 5 (최근 30일)
Brittany Toohey
Brittany Toohey 2017년 4월 9일
댓글: Jan 2017년 4월 9일
I'm trying to plot the difference between two values against an integer, but I get the error "Difference order N must be a positive integer scalar" when using diff. I currently have a function to estimate the volume of a sphere, and another to compare it to the real volume and plot it. Below is my code:
.m
function volume = approximate(b)
for k = 0:b
sum = ((-1).^k) / (2 * k + 1);
end
radius = 46.8;
volume = 4/3 * (4 * sum) * radius.^3;
end
difference.m
b = 0:1:10;
radius = 46.8;
trueValue = (4/3) * pi * radius.^3;
for i = 1:length(b)
difference = diff(approximate(i), trueValue);
end
plot(b, difference);

채택된 답변

Jan
Jan 2017년 4월 9일
편집: Jan 2017년 4월 9일
Did you read the documentation of diff already?
doc diff
It calculates the difference between neighboring elements of a vector and the 2nd input is the difference order.
The code contains more problems:
  1. Do not use "sum" as a name of a variable. This shadows the builtin function with the same name and this causes unexpected behavior frequently.
  2. approxvol is undefined. What about replying a vector from your function approximate?
  3. I assume you want simply: difference = approxvol(i) - trueValue, but this overwrites difference in each iteration. Either use difference(i) = approxvol(i) - trueValue or better omit the loop:
difference = approxvol - trueValue;
Matlab can work with vectors directly.
  댓글 수: 2
Brittany Toohey
Brittany Toohey 2017년 4월 9일
I thought diff might have been wrong, subtraction just wasn't working either. Sorry, I realised I had misnamed something in the post and have now edited it, approxvol should have actually been approximate. So I have to use approximate(i) rather than just approximate as I have to enter an argument into the function.
Thank you very much for clearing this up for me.
Jan
Jan 2017년 4월 9일
Note that both loops in your code a meaningless, because they overwrite the output in each iteration.
function volume = approximate(b)
for k = 0:b
sum = ((-1).^k) / (2 * k + 1);
end
Perhaps you mean:
function volume = approximate(b)
S = 0;
for k = 0:b
S = S + ((-1).^k) / (2 * k + 1);
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Volume Visualization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by