Using index data to fill a matrix

42 ビュー (過去 30 日間)
DrEamonn
DrEamonn 2019 年 2 月 15 日
コメント済み: Jan 2019 年 2 月 15 日
I have a matrix which I have extracted from an Excel file that contains [row_location, column_location, data]. The row and column are non conituous, so the matrix looks like this:
ExtractedData =
[8] [93] [0.1981]
[8] [94] [0.2209]
[8] [95] [0.2276]
[8] [96] [0.2276]
[9] [49] [0.2773]
[9] [50] [0.3941]
[9] [51] [0.3256]
[9] [52] [0.3135]
[9] [53] [0.2343]
[9] [54] [0.3337]
I know how big the full matrix would be from
MaxRow = max(ExtractedData(:, 1))
MaxCol = max(ExtractedData(:, 2))
So I create a NaN matrix of the size
DataToPlot = NaN(MaxRow MaxCol)
& then I would like to populate the correct entry in the DataToPlot matrix with the data from the spreadsheet i.e.
DataToPlot(8, 93) = 0.1981
DataToPlot(8, 94) = 0.2209
DataToPlot(8, 95) = 0.2276
etc
I can see that I want to use a loop to step through the ExtractedData one row at a time, but then I'm unsure of how to extract & use the index data to populate the correct location with the data.
The end goal is to generate a surface plot of the data so if there are any shortcuts or 'best practice' ways of going from extacted data to surface plot I'd appreciate a steer in the right direction.

採用された回答

Jan
Jan 2019 年 2 月 15 日
編集済み: Jan 2019 年 2 月 15 日
This works with a loop easily:
D = ExtractedData; % Easier to read...
MaxRow = max(D(:, 1));
MaxCol = max(D(:, 2));
ToPlot = NaN(MaxRow, MaxCol);
for k = 1:size(D, 1)
ToPlot(D(k, 1), D(k, 2)) = D(k, 3);
end
But it is smarter to do this by sub2ind (link):
MaxSize = max(D(:, 1:2), [], 1); % Get size as vector
ToPlot = NaN(MaxSize);
index = sub2ind(MaxSize, D(:, 1), D(:, 2)); % [EDITED, Typo: D(:,1) -> D(:,2)]
ToPlot(index) = D(:, 3);
  3 件のコメント
Jan
Jan 2019 年 2 月 15 日
編集済み: Jan 2019 年 2 月 15 日
[MOVED from section for answers] DrEamonn wrote:
I think I fixed the problem - it was a resize function elsewhere in my code to remove a text header
Thanks for you help Jan
Eamonn
Jan
Jan 2019 年 2 月 15 日
You are welcome. I've fixed the typo now.
Please use the section from comments to post a comment.

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

その他の回答 (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