Cell array and strings

1 次查看(过去 30 天)
J.S.
J.S. 2018-6-19
I have initialized a series of vectors named vector1, vector2, ... vector8, and am using the code below.
for k=1:numVecs
myCell{1,k}=sprintf('vector%d',k);
myCell{2,k}=???
end
I want to put, in the second row, kth entry of the cell, the content of variable vectork, where k=1,2, etc. I tried:
myCell{2,k}=(strcat('vector',num2str(k)),1:8),
but MATLAB says "Expression or statement is incorrect--possibly unbalanced (, {, or [." right before the 1. Does anyone have a suggestion? Thanks in advance.
  3 个评论
J.S.
J.S. 2018-6-19
Simply typed at the top of my code:
vector1=[1,4,5]; vector2=[4,18,7];
....
etc. This is intentional. The user is intended to manually edit the contents of the vectors to fit the situation
Stephen23
Stephen23 2018-6-20
"I have initialized a series of vectors named vector1, vector2, ... vector8"
If you are creating numbered variables then you are doing something wrong. Trying to access numbered variables is one way that beginners force themselves into writing slow, complex, buggy code. Read this to know why:
Indexing is very neat, very simple, very easy to write, very easy to debug. You should be using indexing, because then your code would be simpler, more efficient, and you avoid this entire situation:
vec{1} = ...
vec{2} = ...
vec{3} = ...
Or if the vectors are the same size then put them into one matrix:
mat(:,1) = ...
mat(:,2) = ...
mat(:,3) = ...
In both cases you can trivially and efficiently access the required data using indexing.

请先登录,再进行评论。

回答(1 个)

OCDER
OCDER 2018-6-19
Your vector1, vector2, etc naming scheme will lead to a lot of headaches and you'll end up recoding everything. See the simple fix below.
Instead of :
vector1 = [1, 4, 5];
vector2 = [4 18 17];
Do this:
vector{1} = [1, 4, 5];
vector{2} = [4 18 17];
To access "vector1", use "vector{1}".
If you want a 2xN cell storing a variable name on row 1, the vector on row 2, then do this:
vecnames = strsplit(sprintf('vector%d;', 1:length(vector)), ';');
C = vertcat(vecnames(1:length(vector)), vector);
C =
2×2 cell array
'vector1' 'vector2'
[1×3 double] [1×3 double]
  7 个评论
OCDER
OCDER 2018-6-20
t1 = 0.0540
t2 = 0.0702
t3 = 0.0526
Version 2017a. Maybe compose got more lines of codes in 2017a+ ?
Yair Altman
Yair Altman 2018-6-29
Note that compose is not a full replacement for sprintfc, although it does cover the most common use-case. Specifically, sprintfc's 3rd [isImaginary] input flag, and its 2nd/3rd output args [errorMsg and isLeft] are not supported by compose.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Historical Contests 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by