Create cell array with the same string n-times

조회 수: 824 (최근 30일)
Olli
Olli 2011년 10월 2일
이동: Dyuman Joshi 2024년 2월 28일
Hi all,
I have another problem I haven't found any soulution for yet.
I have a list of Values and I have the name of the .mat-file the values are saved in as a string.
For example
name='Values.mat'
values =
1
2
3
4
5
Now I need to create a cell array with the name of the file for each value.
For example
>> values.filename
ans =
Values.mat Values.mat Values.mat Values.mat Values.mat
Does anybody know how I can create that cell array, size depending on how many values I have?
Thanks a lot! Oli

채택된 답변

Daniel Shub
Daniel Shub 2011년 10월 2일
The names of your variables are a little confusing ... You are starting with values being a double array and then wanting values to be a structure ...
To answer your question you can create a cell array with the same string n-times with deal.
doc deal
Specifically you can make a 1x5 cell array filename have the value saved in name with:
[filename{1:5}] = deal(name);
you may want to consider a structure array ...
values = struct('value', mat2cell(values, 1, ones(5, 1)), 'filename', name)
  댓글 수: 2
Olli
Olli 2011년 10월 2일
이동: Dyuman Joshi 2024년 2월 28일
Thanks a lot! Sorry for the confusing description, but your responses were very helpful! Oli
morteza HEIDARI
morteza HEIDARI 2017년 2월 13일
thank you man. it was helpful.

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

추가 답변 (3개)

Jan
Jan 2011년 10월 2일
C = cell(1, 5);
C(:) = {'String'};
  댓글 수: 11
Rob
Rob 2021년 12월 17일
Nice simple solution but it baffles me why Matlab needs two lines of code to do a simple task (or why the default is to set the contents as doubles)?
M_A_C
M_A_C 2024년 2월 28일
Hello Jan,
Your elegant solution worked for me using the function strings.

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


Grzegorz Knor
Grzegorz Knor 2011년 10월 2일
repmat({'filename.mat'},1,5)

dscharf
dscharf 2023년 8월 17일
편집: Dyuman Joshi 2024년 2월 28일
Riff'ing on @Jan's answer and noting @Rob's comment,
c(1:5) = {'string'}
c = 1x5 cell array
{'string'} {'string'} {'string'} {'string'} {'string'}
gives a 1x5 in one line (assuming c hasn't been defined before) and
d(1:5,1) = {'string'}
d = 5x1 cell array
{'string'} {'string'} {'string'} {'string'} {'string'}
gives a 5x1. Or at least they do in 2022a.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by