Subscript indices must either be real positive integers or logicals.while using indexing

Hi all,
After performing some processing, now the variable 'a' contains [2 5 9].
Let say i have another variable 'b', variable 'b' is pre-initialized to be zero depending on a length of input, let say 10. b = [0 0 0 0 0 0 0 0 0 0];
What I want is, the elements that are stated in variable 'a' should be set ONE in variable 'b'. b= [0 1 0 0 1 0 0 0 1 0]
I did make sure variable 'a' contains only positive integers.
have added this line "a=round(a); b(a)=1;"
'a' can only be positive integers, I confirm and have checked.
I still I got the same error... Appreciate any idea, thanks

 채택된 답변

Use clear all and then copy-paste-execute
a = [2 5 9];
b = [0 0 0 0 0 0 0 0 0 0];
b(a) = 1
Does that do the trick?

댓글 수: 4

Thank you again, Mischa Kim.
I think my problem lies with that variable 'a' needs to be initialized with zeros at the beginning of m file (where a = zeros(1,10);), how could I avoid this? so that 'a' is [2 5 9] instead of [2 5 9 0 0 0 0 0 0 0]?
If I do not have this line (a = zeros(1,10);), I will get this error (Undefined function or variable "a".)
You mean, cutting off all the zeros?
a = [2 5 9 0 0 0 0 0 0 0]
a(a==0) = []
I tried by replacing this line a = zeros(1,10); with a =[];
still running to see if it works

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Are you sure they are positive and larger than zero ? … I am pretty sure they are not!
remove the semi-colon to see
a = round(a)
b(a) = 1

댓글 수: 1

Thanks, sorry for my careless mistake, please forgive, there are zero which i overlooked.
As mentioned in the post, initially b = [0 0 0 0 0 0 0 0 0 0]; and variable 'a' is [2 5 9 0 0 0 0 0 0 0] after b(a)=1; variable 'b is now b= [0 1 0 0 1 0 0 0 1 0].
variable 'a' needs to be initialized with zeros at the beginning of m file, how could I avoid this? so that 'a' is [2 5 9] instead of [2 5 9 0 0 0 0 0 0 0]?

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2014년 2월 17일

댓글:

2014년 2월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by