Two easy questions (But I am confused)
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
更多回答(1 个)
Les Beckham
2022-7-28
编辑:Les Beckham
2022-7-28
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 个评论
Steven Lord
2022-7-28
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!