Reputation: 107
I wrote the following problem in Matlab to get the first 3 digits of a number.
Let x be a real number.
function [y]=mifl(x) % mifl=my float
s=num2str(x);
y=sscanf(s(1:4),'%f');
end
So function mifl returns the first 3 digits of a number. For example,
mifl(pi)=3.14
But when I tried to apply this function to all the values of the vector v I got "Index exceeds matrix dimensions". I can't figure out why.
I used
v=linspace(0.1, 99.9, 1000);
w=[]
for i=1:5
w(i)=mifl(v(i))
end
That's when I get the "Index exceeds matrix dimensions".
At the end, what I want is, given a vector
v=linspace(0.1, 99.9, 1000);
to get a vector
w=[mifl(0.1),...mifl(99.9)]
Upvotes: 1
Views: 113
Reputation: 4558
You can use Matlabs rand
function.
y = round(x,3,'significant');
This will return the first 3 significant digits of each number in a vector x
. This code will also be easy for another person to comprehend since round is a built in Matlab function, which is used for rounding. The argument 'significant'
should be clear enough. This will also work for numbers larger than 100, which makes it more general. That is of course if it was 3 significant digits you were after and not the first three digits in the number. In that case this will not work. The number 1001 would then be 1000 and not 100, which your solution would give.
Upvotes: 0
Reputation: 104565
The reason is because you are specifying a number in your function that doesn't have three significant digits. Specifically, try 0.1
from your vector. This doesn't have 3 digits and so you get an out of bounds error because you're assuming it does.
As such, in your function, check the length of the string and ensure that there are 4 characters to extract. If not, then get whatever is available:
function [y]=mifl(x) % mifl=my float
s=num2str(x);
m = min(numel(s), 4); %// Change
y=sscanf(s(1:m),'%f');
end
If you try the above, your code should now work.
I'd like to also suggest that you pre-allocate your arrays before populating them for speed.
Specifically:
v=linspace(0.1, 99.9, 1000);
w=zeros(numel(v),1);
for i=1:numel(v)
w(i)=mifl(v(i));
end
w
is initialized to be an array of 0s that is as long as v
, then we'll go through each value in v
and call mifl
, then store this result in the corresponding location in w
.
Upvotes: 2