Effacer les filtres
Effacer les filtres

Cell array and strings

1 vue (au cours des 30 derniers jours)
J.S.
J.S. le 19 Juin 2018
Commenté : Yair Altman le 29 Juin 2018
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 commentaires
J.S.
J.S. le 19 Juin 2018
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 le 20 Juin 2018
"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.

Connectez-vous pour commenter.

Réponses (1)

OCDER
OCDER le 19 Juin 2018
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 commentaires
OCDER
OCDER le 20 Juin 2018
t1 = 0.0540
t2 = 0.0702
t3 = 0.0526
Version 2017a. Maybe compose got more lines of codes in 2017a+ ?
Yair Altman
Yair Altman le 29 Juin 2018
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Historical Contests dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by