Two easy questions (But I am confused)
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ashfaq Ahmed
am 28 Jul. 2022
Kommentiert: Steven Lord
am 28 Jul. 2022
Hi!
- Say I have a matrix S that is of 100x100 size. Now, I want to create an array just by taking the diagonal values of S. So, the matrix will be a 1x100 double. How can I do that using a for loop?
- Say, I want to create a cell that will have strings like 'Row 1', 'Row 2', 'Row 3', ....., 'Row 100'. How can I do that?
0 Kommentare
Akzeptierte Antwort
Matt J
am 28 Jul. 2022
No need for (explicit) loops:
S=rand(100);
Sdiag=diag(S);
cellstr("Row "+(1:100))
Weitere Antworten (1)
Les Beckham
am 28 Jul. 2022
Bearbeitet: Les Beckham
am 28 Jul. 2022
Using smaller examples so we can see the results:
S = magic(10) % sample matrix
d = diag(S) % extract the diagonal elements
% note that this function is undocumented but quite useful for creating cell arrays
sprintfc('Row%d', 1:10)
3 Kommentare
Steven Lord
am 28 Jul. 2022
If you're trying to create an array of text to use as legend entries and you're using a release that supports string, you don't need to create a cellstr for this purpose.
legendStrings = strings(1, 5);
x = 0:360;
axis([0, 360, -1, 1]) % x ranges from 0 to 360, y ranges from -1 to +1
hold on
for k = 1:5
plot(x, sind(k*x))
legendStrings(k) = "sine of " + k + "*x";
end
legend(legendStrings)
Alternately you could set each line's DisplayName property when you create it. If you do that you don't have to maintain a separate list of legend strings. All you'd have to do at the end of your code is tell MATLAB to show the legend. I'm using cosine for this one instead of sine so you see I didn't just copy and paste.
figure
x = 0:360;
axis([0, 360, -1, 1]) % x ranges from 0 to 360, y ranges from -1 to +1
hold on
for k = 1:5
plot(x, cosd(k*x), 'DisplayName', "cosine of " + k + "*x");
end
legend show
Siehe auch
Kategorien
Mehr zu Data Distribution Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!