Using diff() in a for loop

5 visualizzazioni (ultimi 30 giorni)
Brittany Toohey
Brittany Toohey il 9 Apr 2017
Commentato: Jan il 9 Apr 2017
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);

Risposta accettata

Jan
Jan il 9 Apr 2017
Modificato: Jan il 9 Apr 2017
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 Commenti
Brittany Toohey
Brittany Toohey il 9 Apr 2017
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 il 9 Apr 2017
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

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by