필터 지우기
필터 지우기

how to replace double vectors from 0 to '000'

조회 수: 2 (최근 30일)
Mohamuud hassan
Mohamuud hassan 2015년 5월 14일
댓글: Mohamuud hassan 2015년 5월 14일
hello every body; i am dealing with string and number how i can solve this problem: "In an assignment A(I) = B, the number of elements in B and I must be the same." "E_extrac_pro(ex_loop2)='000';" where numbers vector are double and contains:
numbers=[202;0 ;20;0;0;1013;10];
for ex_loop2=1:size(numbers)
if(numbers(ex_loop2)==0)
E_extrac_pro(ex_loop2)='000';
else
E_extrac_pro(ex_loop2)=numbers(ex_loop2);
end
end

채택된 답변

Stephen23
Stephen23 2015년 5월 14일
편집: Stephen23 2015년 5월 14일
Why bother with the loop at all?:
>> numbers=[202;0 ;20;0;0;1013;10];
>> X = num2str(numbers,'%04g')
X =
0202
0000
0020
0000
0000
1013
0010
And if the output must be a cell array:
>> cellstr(X)
ans =
'0202'
'0000'
'0020'
'0000'
'0000'
'1013'
'0010'
  댓글 수: 3
Stephen23
Stephen23 2015년 5월 14일
편집: Stephen23 2015년 5월 14일
Then you can adjust the format string to get the desired result:
>> X = num2str(numbers,'%03g')
X =
202
000
020
000
000
1013
010
>> strtrim(cellstr(X))
ans =
'202'
'000'
'020'
'000'
'000'
'1013'
'010'
The num2str documentation clearly explains these formatting options. Or you could put it in an arrayfun with sprintf:
>> arrayfun(@(n)sprintf('%03g',n), numbers, 'UniformOutput',false)
ans =
'202'
'000'
'020'
'000'
'000'
'1013'
'010'
Mohamuud hassan
Mohamuud hassan 2015년 5월 14일
thank you stephen.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2015년 5월 14일
To mix strings and numbers in the same array, you'll have to use a cell array:
E_extrac_pro = cell(1, size(numbers));
for ex_loop2=1:size(numbers)
if(numbers(ex_loop2)==0)
E_extrac_pro{ex_loop2}='000';
else
E_extrac_pro{ex_loop2}=numbers(ex_loop2);
end
end
For more info, see FAQ: What is a cell array
  댓글 수: 1
Mohamuud hassan
Mohamuud hassan 2015년 5월 14일
편집: Mohamuud hassan 2015년 5월 14일
i applied your idea but with new error: Cell contents assignment to a non-cell array object. E_extrac_pro{ex_loop2}=numbers(ex_loop2);

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by