Ceate a x b matrix (or 2D array) from 2 1Darrays, and populate each cell from another array

조회 수: 8 (최근 30일)
So I have 3 arrays; say a,b,c. a and b represent distances, and c represents a variable with a specific value at the point (a,b).
I have been trying to create a matrix which comprises of (b x a) cells, and the populate it with the values of c, in order to then image, heatmap it etc.
However the issue I have having is that there are many repeating values of a and b; a stays fixed and it then iterates across all values of b, then moves onto the next value of a, and so forth. The range of a and b is fixed and always iterate across equally spaced values though.
Below is the code I have created for this. So for it seems to not to work and I am out of ideas.
z_true_len = length(unique(a)); %number of z distances
r_true_len = length(unique(b)); %number of r disatances
data_matrix = zeros(r_true_len,z_true_len); %create r x z matrix, full of 0s
z_past = 0;
r_past = 0;
z_count = 1;
r_count = 1;
for count = 1: length(a)
z_current = a(count);
if z_past ~= z_current
data_matrix(1:z_count) = c(count);
z_past = z_current;
z_count = z_count + 1;
r_count = 1;
else
data_matrix(r_count:z_count) = c(count);
r_count = r_count + 1;
end
end
data_matrix
I have also tried the simplier:
a = [1 1 1 1 2 2 2 2 3 3 3 3];
b = [1 2 3 4 1 2 3 4 1 2 3 4];
c = [0 2 1 0 0 4 6 8 4 2 0 0];
z_true_len = length(unique(a));
r_true_len = length(unique(b));
data_matrix = zeros(r_true_len,z_true_len);
for count = 1:length(a),
data_matrix(b(count),a(count)) = c(count);
end
figure;
imagesc(data_matrix)
However this will only work if a,b and c contatin interger values, which sadly they do not.

답변 (1개)

Ahmet Cecen
Ahmet Cecen 2014년 8월 14일
편집: Ahmet Cecen 2014년 8월 14일
[X,Y] = meshgrid(xgv,ygv)
is your friend.
You can also do it another way, let say your x range is 1 to 5 and y range is 1 to 6, and I am also assuming x goes 1 1 1 1 1 1 while y goes 1 2 3 4 5 6 and so on:
X=reshape(x,[6 5]);
Y=reshape(y,[6 5]);
C=reshape(c,[6 5]);
surf(X,Y,C);
  댓글 수: 7
Ahmet Cecen
Ahmet Cecen 2014년 8월 14일
I would avoid trying to edit it programmatically. Use the GUI after surf to modify the colors, axes etc, then use file->generate code to spit out a function that will have your visual modifications coded in automatically. You would then use the new function to plot subsequent results.
Check:

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by