adding a matrix layer to an already existing matrix

3 ビュー (過去 30 日間)
Andrew Poissant
Andrew Poissant 2017 年 4 月 10 日
コメント済み: Andrew Poissant 2017 年 4 月 10 日
I want to add a layer to my 180x180 matrix, seen below. N is where I define the actual matrix in the code. I want to add a layer to make it a 3D matrix such that the second layer has a cell value of 0 at (90,90) and increases by 1 for increasing i and j indices, and decreases by 1 for decreasing i and j indices. So I am essentially setting up a cartesian coordinate plane with the second layer. so the index (91,90) should have a value of 1, (92,90) a value of 2, (89,90) a value of -1, (90,91) a value of 1, etc. Any ideas?
N1 = randi([1,500],45,45);
N2 = randi([25,1000],45,45);
N3 = randi([100,2200],45,45);
N4 = randi([5,700],45,45);
N5 = randi([100,500],45,45);
N6 = randi([800,3500],45,45);
N7 = randi([1000,10000],45,45);
N8 = randi([15,1000],45,45);
N9 = randi([250,900],45,45);
N10 = randi([5000,11000],45,45);
N11 = randi([1750,9000],45,45);
N12 = randi([25,890],45,45);
N13 = randi([2000,7500],45,45);
N14 = randi([200,2300],45,45);
N15 = randi([25,750],45,45);
N16 = randi([50,1323],45,45);
N = [N1 N2 N3 N4;
N5 N6 N7 N8;
N9 N10 N11 N12;
N13 N14 N15 N16];

採用された回答

Stephen23
Stephen23 2017 年 4 月 10 日
M(:,:,2) = bsxfun(@plus,-89:90,(-89:90).');
  5 件のコメント
Stephen23
Stephen23 2017 年 4 月 10 日
編集済み: Stephen23 2017 年 4 月 10 日
Some reasons:
  1. Each of those variables N1, N2, etc, gets used once and then just clutters up your memory (and workspace) unnecessarily. The values are probably stored twice in memory (although MATLAB is cunning sometimes...).
  2. Often numbered variables lead to dynamic variable names (not in this case, but it really is best to avoid getting into that trap).
  3. Code that is more generalized (i.e. does not rely on hard-coded numbers, etc) is easier to adapt and is more useful. A cell array might be useful for this case.
Code is always a compromise, so if visualizing is critical to getting it right then that is okay too. So my comment was not a critical point, unless you are really trying to be careful with memory and are working with large arrays (as some of us do).
Andrew Poissant
Andrew Poissant 2017 年 4 月 10 日
Thank you for the info, I will use your suggestions.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by