what is the best mode to populate this array in this loop annidate?

1 vue (au cours des 30 derniers jours)
pipor
pipor le 11 Sep 2023
Commenté : pipor le 11 Sep 2023
i want to code it to creare text for legend plot! (legend)
it's better to use string and strcat or use arraycell ?
if the better is the second how can i do it?
or is it better to create the text outside the nested loop?
str1="a";
wA=1;
str2="b";
wB=1;
n=5;
b=2;
valA=rand(n,1,1) %it's only for example..i don't use it :)
valA = 5×1
0.4488 0.3232 0.4840 0.9989 0.2870
valB=rand(b,1,1)
valB = 2×1
0.3478 0.2064
clear str
count=0;
strtot="";
for i=1:n
for k=1:b
count=count+1;
if wA==1
strtot=strcat(str1,"-",num2str(valA(i)))
end
if wB==1
strtot=strcat(strtot," ** ",str2,"-",num2str(valB(k)))
end
strArr(count,:)=strtot;
end
end
strtot = "a-0.44885"
strtot = "a-0.44885 ** b-0.34784"
strtot = "a-0.44885"
strtot = "a-0.44885 ** b-0.20644"
strtot = "a-0.32321"
strtot = "a-0.32321 ** b-0.34784"
strtot = "a-0.32321"
strtot = "a-0.32321 ** b-0.20644"
strtot = "a-0.48396"
strtot = "a-0.48396 ** b-0.34784"
strtot = "a-0.48396"
strtot = "a-0.48396 ** b-0.20644"
strtot = "a-0.99888"
strtot = "a-0.99888 ** b-0.34784"
strtot = "a-0.99888"
strtot = "a-0.99888 ** b-0.20644"
strtot = "a-0.28696"
strtot = "a-0.28696 ** b-0.34784"
strtot = "a-0.28696"
strtot = "a-0.28696 ** b-0.20644"

Réponses (1)

Dyuman Joshi
Dyuman Joshi le 11 Sep 2023
It would be better to use string instead of cells as they take less memory and easier to work with -
n=5;
b=2;
valA=rand(n,1,1) %it's only for example..i don't use it :)
valA = 5×1
0.1930 0.5700 0.8833 0.6422 0.7329
valB=rand(b,1,1)
valB = 2×1
0.6020 0.5495
[A,B] = meshgrid(valA,valB);
"a-" + string(A(:)) + " ** b-" + string(B(:))
ans = 10×1 string array
"a-0.19302 ** b-0.60203" "a-0.19302 ** b-0.54955" "a-0.56996 ** b-0.60203" "a-0.56996 ** b-0.54955" "a-0.88331 ** b-0.60203" "a-0.88331 ** b-0.54955" "a-0.64219 ** b-0.60203" "a-0.64219 ** b-0.54955" "a-0.73285 ** b-0.60203" "a-0.73285 ** b-0.54955"
  3 commentaires
Dyuman Joshi
Dyuman Joshi le 11 Sep 2023
Modifié(e) : Dyuman Joshi le 11 Sep 2023
I am well aware that your code is different and that you have used wA and wB in your code inside the for loop, but I was giving a general example.
You can always modify the code according to requirement.
Let's consider that the input are -
A = [2 3 5 7];
B = [1 4 6 8];
What should be the output if
1 - wA is zero and wB is one?
2 - wA is one and wB is zero?
3 - wA is one and wB is one?
pipor
pipor le 11 Sep 2023
yes...it can be like your example but I solved it as a post I wrote.. Thanks anyway for the help

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings 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