I have a 2D array and I want to create a 1D by MATLAB, satisfying the requirement that each element of the 1D output was created by the value of a given index into the 2D array.
You can use cellfun
to do it. You convert A into cell by column, and execute f
for each element of the cell.
A=[2 4 6; 1 2 7];
% some example f funcion that just adds the col_index_A and row_index_A
f = @(col_index_A, row_index_A) col_index_A + row_index_A;
% execute f with parameters that come from each column of A
B = cellfun(@(c) f(c(1), c(2)), num2cell(A, 1));
B =
3 6 13
I am not sure I understand your question but i think you want to apply functions on a 2-by-n matrix
Try
for pos=1:size(a,2)
b(pos) = f(a(:,pos));
end
You are looking for sub2ind:
A=[2 4 6; 1 9 7; 3 4 5]
X=[1;2;3]; Y=[1;2;3];
B = A(sub2ind(size(A),X,Y))
B =
2
9
5