get error when remove an item

조회 수: 5 (최근 30일)
huda nawaf
huda nawaf 2012년 3월 2일
hi, i want to remove an item from array, but get error
this is my code
align(1,:)='asd-as---tyr';
align(2,:)='fg--ds--h-ty';
for i=1:12
if align(1,i)=='-' & align(2,i)=='-'
align(1,i)=[]; align(2,i)=[];
end
end
??? A null assignment can have only one non-colon index.
Error in ==> testt at 6
align(1,i)=[];
thanks in advance

채택된 답변

Jan
Jan 2012년 3월 2일
When you remove a character, the string is getting shorter. But the FOR-loop tries to access all characters of the initial size.
Either run the loop in reverse direction:
align(1,:) = ['asd-as---tyr'; ...
'fg--ds--h-ty'];
for i=12:-1:1
if align(1,i)=='-' & align(2,i)=='-'
align(:,i) = [];
end
end
Or use a vectorized approach, which is faster and nicer:
align(align(1, :)=='-' & align(2, :)=='-', :) = []; % No FOR loop, no IF
[EDITED]: Typo in the line above (thanks Walter!):
align(:, align(1, :)=='-' & align(2, :)=='-') = [];
  댓글 수: 3
Walter Roberson
Walter Roberson 2012년 3월 2일
align(:, align(1, :)=='-' & align(2, :)=='-') = []; % No FOR loop, no IF
huda nawaf
huda nawaf 2012년 3월 2일
many many thanks walter

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

추가 답변 (2개)

Aurelien Queffurust
Aurelien Queffurust 2012년 3월 2일
To remove the minus sign you could use:
align= char(strrep(align(1,:),'-','') ,strrep(align(2,:),'-','') )

the cyclist
the cyclist 2012년 3월 2일
I can see how you would find that error message a bit cryptic, but here is what is going on.
Your variable align is a 2x12 character array. With your line of code
align(1,i)=[];
is going to attempt to remove the upper-left corner of that array. But MATLAB can't do that. There cannot be a character array that has one row of 11 elements, and a second row that is 12 elements. One element cannot be "empty" in that way. (That is what error message is saying.) You can only do the null assignment for a whole row or column at once.
So, in your case, you could combine your two null assignment statements into the single statement
align(:,i) = [];
and MATLAB will delete the i'th column, in its entirety.
Be aware that your array align is going to keep getting trimmed, as it goes through the for loop, so it will no longer be width 12.
  댓글 수: 3
Jan
Jan 2012년 3월 28일
Please post a new question in a new thread.
huda nawaf
huda nawaf 2012년 3월 28일
okay, but erlier walter said to me if the new question relate previous thread do not send new thread

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by