How to print result in MATLAB?

Dear everyone,
Please help me to solve this problem. I have two arrays like this:
Name=['ABC-8' 'S8' 'EG8'];
Thick=[25 16 12];
I want to create an array like this:
Z=['ABC-825' 'S816' 'EG812'];
Can anyone help me to write a code to make that array?
Thank you so much!

 採用された回答

Aniruddha Phatak
Aniruddha Phatak 2014 年 8 月 21 日

0 投票

Robert is right, you must define it as a cell array.
name={'ABC-8' 'S8' 'EG8'};
thick=[25 16 12];
for i=1:3
thin{i} = [ num2str( thick(i) ) ];
z{i} = strcat(name{i},thin{i});
end
disp(z);

その他の回答 (3 件)

David Sanchez
David Sanchez 2014 年 8 月 21 日

1 投票

define your Name array as a cell, then:
Name={'ABC-8' 'S8' 'EG8'};
Thick=[25 16 12];
Z =cell(numel(Name),1);
for k=1:numel(Name)
Z{k} = strcat(Name{k},num2str(Thick(k)));
end
>> Z
Z =
'ABC-825'
'S816'
'EG812'

1 件のコメント

Phan
Phan 2014 年 8 月 21 日
Thank you so much!

サインインしてコメントする。

Guillaume
Guillaume 2014 年 8 月 21 日
編集済み: Guillaume 2014 年 8 月 21 日

1 投票

Assuming that Name is a cell array, that is
Name = {'ABC-8' 'S8' 'EG8'};
(otherwise as you wrote it, it's just a single string). Then:
Z = cellfun(@(s,n) sprintf('%s%d', s, n), Name, num2cell(Thick), 'UniformOutput', false);
will do it. Note that Z has to be a cell array.

1 件のコメント

Phan
Phan 2014 年 8 月 21 日
Thank you so much!

サインインしてコメントする。

Robert Cumming
Robert Cumming 2014 年 8 月 21 日

1 投票

The two answers on here are correct - however if you take the for loop from one and the sprintf from the other you get a faster result:
Z =cell(1,numel(Name));
for k=1:numel(Name)
Z{k} = sprintf ( '%s%d', Name{k}, Thick(k) );
end
Speed evidence:
clear
clc
Name={'ABC-8' 'S8' 'EG8'};
Thick=[25 16 12];
tic
ZA =cell(1,numel(Name));
for k=1:numel(Name)
ZA{k} = strcat(Name{k},num2str(Thick(k)));
end
toc
tic
ZB = cellfun(@(s,n) sprintf('%s%d', s, n), Name, num2cell(Thick), 'UniformOutput', false);
toc
tic
ZC =cell(1,numel(Name));
for k=1:numel(Name)
ZC{k} = sprintf ( '%s%d', Name{k}, Thick(k) );
end
toc
isequal ( ZA, ZB )
isequal ( ZA, ZC )
Elapsed time is 0.011248 seconds.
Elapsed time is 0.011344 seconds.
Elapsed time is 0.006111 seconds.

3 件のコメント

Guillaume
Guillaume 2014 年 8 月 21 日
I'd rather have the clarity of intent of cellfun / arrayfun over writing the loop myself, but at least Phan's got the choice.
Robert Cumming
Robert Cumming 2014 年 8 月 21 日
For this type of question you could solve it in many ways....
I just highlight this as many people overlook the simple for loop and the fact that sprintf is the fastest way for handling strings...
Phan
Phan 2014 年 8 月 21 日
Thank you all! You helped so much!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeTables についてさらに検索

質問済み:

2014 年 8 月 21 日

コメント済み:

2014 年 8 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by