Save real numbers (with decimals) in a loop into vector.
Show older comments
Dear All, I asked a question yesterday, but I wasn't so clear and believe that the information in the post got complicated and many would avoid looking at it~ I rephrase my problem very shortly:
Normally, if 'i' is a vector of positive integers, the vector of its product say 'i*rand' would be easy to get:
i=1:5;
y(i)=i*rand
y =
0.4468 0.8935 1.3403 1.7871 2.2339
But if 'i' is just a real number, say:
i=0.1:0.5;
y(i)=i*rand
Attempted to access y(0.1); index must be a positive integer or logical.
Question:
How do I overcome this problem and get 'y', the vector of the product 'i*rand'.
Thanks and Best of Regards// Ali
Accepted Answer
More Answers (1)
Jan
on 4 Jan 2013
You can simply omit the index on the left hand side:
ii = 0.1:0.5;
y = ii * rand
After this, you cannot access "y(0.1)", because index expressions must be integers. But you could create a function:
function r = y(x)
r = rand * x;
Now "y(0.1)" calculates the function for this value, but this is not exactly equivalent to the indexing in your example. But usually this is a sufficient solution.
When you really need to use a floating point value as index, you will get problems with FAQ: limited floating point precision:
any(0:0.1:1 == 0.3)
>> 0
This is not a bug, but cause by the fact, that not all decimal numbers can be represented exactly in binary format. Therefore any kind of floating-point-indexing would require a comparison like find(abs(v - value) < 100*eps). The limit of 100*eps is more or less arbitrary and depend on the values. In consequence the required code for indexing must be smart and need intelligent fallbacks.
Better stay on integer indexing.
2 Comments
You can then simply get an index vector with the same length as the non-integer indeces:
str = {'.1' '.2' '.3' '.4' '.5'};
ii = str2double(str);
y = ii*rand
ind = 1:length(y)
AND
on 4 Jan 2013
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!