필터 지우기
필터 지우기

How to populate a matrix based on a function?

조회 수: 6 (최근 30일)
Shaun Pedicini
Shaun Pedicini 2018년 3월 4일
댓글: Walter Roberson 2020년 8월 23일
I have a 2d matrix of width 256 and height 128.
I also have some theoretical function: 127.5 * cos(pi * row_index) + col_index
I want to populate the cells of the matrix using this function so that the row_index/col_index pull from each cell as it is computed.
Ideally I need to use functions that can run against each cell in a matrix and also have access to the following variables:
  1. Current Column Index
  2. Current Row Index
  3. Current Cell Value (I'm not using this in the earlier example, but I'd like to be able to use it in the future)

채택된 답변

Walter Roberson
Walter Roberson 2018년 3월 4일
[RowIndices, ColumnIndices] = ndgrid(1:size(YourArray,1), 1:size(YourArray,2));
population_function = @(col_idx, row_idx, CurrentCellValue) 127.5 * cos(pi * row_index) + col_index;
populated_matrix = arrayfun(population_function, ColumnIndices, RowIndices, YourArray);
... But you will find that it is more efficient to just use vectorization:
[col_index, row_index] = ndgrid(1:size(YourArray,1), 1:size(YourArray,2));
populated_matrix = 127.5 * cos(pi * row_index) + col_index;
  댓글 수: 4
s s
s s 2020년 8월 23일
It's so cumbersome to do this in matlab compared with the Mathematica function "Table".
Walter Roberson
Walter Roberson 2020년 8월 23일
You can also use
col_index = 1:size(YourArray,1);
row_index = 1:size(YourArray,2);
populated_matrix = 127.5 * cos(pi * row_index(:)) + col_index;

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Language Support에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by