How to store string into an array?

조회 수: 119 (최근 30일)
Minu
Minu 2013년 6월 4일
Hi
How to save string into array.I have string of characters and want to save in an array.
y(1)='0D05';
y(2)='0D06';
y(3)='0D10; and so on...How to solve this

답변 (3개)

Chandrasekhar
Chandrasekhar 2013년 6월 4일
try this Minu y= {'0D05','0D06','0D10'};
if u want to update the array during run time
y{i} = {str};
  댓글 수: 3
Chandrasekhar
Chandrasekhar 2013년 6월 4일
I have entered the following commands on matlab command window and its working.
>> y= {'0D05','0D06','0D10'}; >> i = 4
i =
4
>> y{4} = '0D11'
y =
'0D05' '0D06' '0D10' '0D11'
Jan
Jan 2013년 6월 4일
@Minu: Please care for always posting a complete copy of the message accompanied by the relevant part of the corresponding code. Without seeing the code, we would have to guess suggestions for improvements. Thanks.

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


Daniel Shub
Daniel Shub 2013년 6월 4일
You cannot access a string with y(1) easily. The problem is that your data is a character array and not a string array. This means that the notation y(1) is asking for a single element of a character array, which is a single character, but you want a string.
Assuming you are starting with some data that looks like
x = char(randi([1, 26]+64, 1, 4*10))
You can rearrange it to have the shape you want by putting 4 characters on a row.
y = reshape(x, [], 4);
You can then get a row with
y(1, :)
If you do not want the trailing colon, you could use a cell array
z = mat2cell(y, ones(10, 1), 4);
You can then get a row with
z{1}
If neither of these suffice you can use the OOP system to define your own string class and then you can use y(1) to get a single element of a string object which would be a character array.

Azzi Abdelmalek
Azzi Abdelmalek 2013년 6월 4일
편집: Azzi Abdelmalek 2013년 6월 4일
y=char('0D05','0D06','0D10');
%or
y=cellstr(char('0D05','0D06','0D10'));
  댓글 수: 1
Jan
Jan 2013년 6월 4일
In the first case, char can be omitted and replaced by square brackets. In the second case char can be omitted without any replacement.

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

카테고리

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