MATLAB Data from loop not saved

1 view (last 30 days)
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

Accepted Answer

Simon
Simon on 6 Dec 2013
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 Comment
Patrick Allaglo
Patrick Allaglo on 6 Dec 2013
Hi thx for your answer, i just understood the mistake i made... Thx again

Sign in to comment.

More Answers (1)

Wayne King
Wayne King on 6 Dec 2013
Edited: Wayne King on 6 Dec 2013
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.
  1 Comment
Patrick Allaglo
Patrick Allaglo on 6 Dec 2013
Edited: Patrick Allaglo on 6 Dec 2013
Hi , thx for answering im just beginning Matlab so im a little bit lost. I understand what you tried to say. Im trying to make a program which calculate the real voltage of an electric circuit with 100 of charge values evolving logarithmically between 1 and 100 ohms. :) thx

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!