- 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.
- approxvol is undefined. What about replying a vector from your function approximate?
- 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:
Using diff() in a for loop
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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);
0 Kommentare
Akzeptierte Antwort
Jan
am 9 Apr. 2017
Bearbeitet: Jan
am 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:
difference = approxvol - trueValue;
Matlab can work with vectors directly.
2 Kommentare
Jan
am 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Volume Visualization finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!