Trying to create a vector in steps of 0.5
269 次查看(过去 30 天)
显示 更早的评论
I'm trying to get the vector to go up in steps of 0.5.
v_numerical(0.5)= g.*0.5;
for i = 1:0.5:10
v_numerical(i) = v_numerical(i-0.5)+(g-((c.*v_numerical(i-0.5))./m).*(0.5));
end
However whenever i try running it I get the error:
Attempted to access v_numerical(0.5); index must be a positive integer or logical.
Any idea how I can solve this problem? Many thanks in advance!
0 个评论
采纳的回答
Stephen23
2016-1-24
编辑:Stephen23
2016-1-24
MATLAB indices start at one, and must be whole numbers (i.e. no fraction allowed). With your code you are trying to index with 0.5 and lots of other fractions, which will always be an error, like this:
>> A(0.5) = 3 % fraction index is an error
??? Attempted to access (0.5); index must be a positive integer or logical.
>> A(1) = 3 % whole number index is okay
A =
3
You can easily create a vector with 0.5 spacing:
V = 1:0.5:10;
but when I tried to fix your code it made very little sense to me what you are trying to achieve. Can you please explain what you are trying to do with this code: what should the input and output be?
更多回答(1 个)
Nemanja
2023-6-9
编辑:Nemanja
2023-6-9
g = linspace(1:10:20) %goes from 1 to 10 and has 20 elements because 10/20 is 0.5 so it will go up from 1 to 10 with 0.5 spacing%
1 个评论
Stephen23
2023-6-9
"goes from 1 to 10 and has 20 elements because 10/20 is 0.5 so it will go up from 1 to 10 with 0.5 spacing"
No, you are making this error:
It is easy to check that your statement is incorrect: did you try running the code yourself before posting here?
g = linspace(1,10,20) % fixed incorrect syntax
Tip: to split the range 1..10 into steps of 0.5 then you need 19 elements. Lets try it now:
g = linspace(1,10,19)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!