Two easy questions (But I am confused)
1 回表示 (過去 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 件のコメント
採用された回答
Matt J
2022 年 7 月 28 日
No need for (explicit) loops:
S=rand(100);
Sdiag=diag(S);
cellstr("Row "+(1:100))
その他の回答 (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!