Two easy questions (But I am confused)
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Ashfaq Ahmed
el 28 de Jul. de 2022
Comentada: Steven Lord
el 28 de Jul. de 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 comentarios
Respuesta aceptada
Matt J
el 28 de Jul. de 2022
No need for (explicit) loops:
S=rand(100);
Sdiag=diag(S);
cellstr("Row "+(1:100))
Más respuestas (1)
Les Beckham
el 28 de Jul. de 2022
Editada: Les Beckham
el 28 de Jul. de 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 comentarios
Steven Lord
el 28 de Jul. de 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
Ver también
Categorías
Más información sobre Data Distribution Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!