MATLAB Data from loop not saved
1 次查看(过去 30 天)
显示 更早的评论
Hi everybody, im actually making a little program wich must give me a graph.
Tens_stored = zeros(100,1);
Tens_S = 12;
Res_I = 10;
Res_E = logspace(0,2,100);
for B = logspace(0,2,100);
Tens = (B.*Tens_S)/(B+Res_I);
disp(Tens)
Tens_stored(B) = Tens;
semilogx(Res_E,Tens_stored)
end
But when i launch it, it make an error : Attempted to access Tens_stored(1.04762); index must be a positive integer or logical.
Error in TEST1 (line 8) Tens_stored(B) = Tens; And no one of the values calculated are in the array Tens_Stored. Can somebody help me plz :) Thx
0 个评论
采纳的回答
Simon
2013-12-6
Hi!
You can not use doubles as indices. Do instead:
Res_E = logspace(0,2,100);
for B = 1:length(Res_E);
Tens = (Res_E(B).*Tens_S)/(Res_E(B)+Res_I);
disp(Tens)
Tens_stored(B) = Tens;
end
semilogx(Res_E,Tens_stored)
Plot after the loop! (Is it right that B and Res_E are the same?)
更多回答(1 个)
Wayne King
2013-12-6
编辑:Wayne King
2013-12-6
You can't have a for loop where the index is non-integers, like this
B = logspace(0,2,100);
because the 2nd element of B is already a non-integer value and you can't access a non-integer element of an array. Think about it. Does it make sense to ask what is the 2.5-th element of a finite-dimensional vector?
Why would you want to space filled elements of a vector logarithmically. even if you could do it with integer values? You would end up with zeros in your vector. For example, if you did
y(1) = 2;
y(3) = 1;
Note that MATLAB makes y a length-3 vector and puts a zero in for the 2nd element.
I'm not sure what you're trying to do here, but maybe something like:
Tens_stored = zeros(100,1);
Tens_S = 12;
Res_I = 10;
Res_E = logspace(0,2,100);
for nn = 1:100
Tens = (Res_E.*Tens_S)/(B+Res_I);
Tens_stored(nn) = Tens;
end
Although the above just gives the same value for Tens_stored at each element of the array, so I'm sure you probably don't want that.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!