Cell array and strings
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Stephen23
il 20 Giu 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.
Risposte (1)
OCDER
il 19 Giu 2018
Take a read here: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
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 Commenti
OCDER
il 20 Giu 2018
t1 = 0.0540
t2 = 0.0702
t3 = 0.0526
Version 2017a. Maybe compose got more lines of codes in 2017a+ ?
Yair Altman
il 29 Giu 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.
Vedere anche
Categorie
Scopri di più su Historical Contests in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!