MATLAB Answers

Subscript indices must either be real positive integers or logicals.

1 view (last 30 days)
dear all
i have code like below
clc
clear all
for b=1:0.1:20
M((b*10)-9,:)=[1 1 1 ]
end
but at b=2.4 i got this error :
M =
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
Subscript indices must either be real positive integers
or logicals.
Error in Untitled2 (line 4)
M((b*10)-9,:)=[1 1 1 ]
i really appreciated if some can help me y i get this error and what the solotions ?

  3 Comments

Adam
Adam on 14 Jan 2019
Why are you using such complex maths for your indices? If you really must do that then use
doc round
e.g.
M( round( (b*10)-9 ), : ) = [1 1 1];
Floating point numbers are not perfectly represented so when you start doing maths with them which, in theory, should result in an integer value in practice does not due to rounding errors caused by how floating point numbers are represented on a computer.
Stephen Cobeldick
Stephen Cobeldick on 14 Jan 2019
"i really appreciated if some can help me y i get this error..."
"...and what the solotions ?"
Do not do calculations on floating point numbers and expect to get exact integer outputs. Write your code knowing that calculations on floating point numbers accumulate floating point error.
shahin hashemi
shahin hashemi on 14 Jan 2019
thank you very much
i use round and got answer
u cooment so i cant accept your answer

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 14 Jan 2019
Edited: Stephen Cobeldick on 14 Jan 2019
Better to iterate over integer indices rather than fractional values:
V = 1:0.1:20;
N = numel(V);
M = nan(N,3);
for k = 1:N
M(k,:) = [1,1,1];
end
Even better:
M = repmat([1,1,1],N,1)
Best:
M = ones(N,3)

  0 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2015b

Community Treasure Hunt

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

Start Hunting!