Making a list from two arrays

조회 수: 3 (최근 30일)
Julien
Julien 2014년 8월 12일
댓글: Julien 2014년 8월 12일
I'm relatively new to coding, and have no clue how I would pull the following off.
Say I have two vectors: A = [a b c d] and B = [1 2 3 4].
I would like to make a function that takes these two as inputs and outputs exactly the following into a .txt file, curly brackets included:
{a->1,b->2,c->3,d->4}
I was thinking some kind of for loop, but I have no experience using them and no idea how I would set this up.
Thanks

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 8월 12일
편집: Azzi Abdelmalek 2014년 8월 12일
A = {'a' 'b' 'c' 'd'}
B = [1 2 3 4]
out='{'
for k=1:numel(B)
out=[out sprintf('%s->%d,',A{k},B(k))]
end
out(end)='}'
%or
A = {'a' 'b' 'c' 'd'}
B = [1 2 3 4]
out=['{' strjoin(cellfun(@(x,y) sprintf('%s->%d',x,y),A,num2cell(B),'un',0),',') '}']
  댓글 수: 1
Julien
Julien 2014년 8월 12일
Thanks, this works exactly as I wanted it to.

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

추가 답변 (1개)

Evan
Evan 2014년 8월 12일
편집: Evan 2014년 8월 12일
How about this?
A = 'abcd';
B = [1 2 3 4];
fid = fopen('my_txt_file','w');
s = [];
for i = 1:numel(A)
s = [s sprintf('%s->%d,',A(i),B(i))];
end
s = ['{' s(1:end-1) '}'];
fprintf(fid,s);
fclose(fid)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by