Reputation: 75
I have a basic txt file that reads as:
0 0 0 40
0 0 1 40
0 1 0 40
0 1 1 40
1 15 15 250
1 15 16 250
1 16 15 250
1 16 15 250
The Columns are as follows:
Class Truth Label
X
Y
Pixel Intensity
I am trying to calculate the Mean Vector for each Class in the file. For this, I am not sure if I can simply do the
meanVector = mean(MyImage);
I am unsure of this because the columns are not all Pixel Densities I suspect that I will be having two mean vectors, for the 0 Class and the 1 Class.
testFile = fopen('test_file.txt', 'r');
sizeOfTestFile = [4 Inf];
testFileMatrix = fscanf(testFile, '%d', sizeOfTestFile);
testFileMatrix = testFileMatrix’
In this code above, I am generating the FileID's for the 'test_file.txt' and creating an 8 x 4 matrix by scanning the original file.
So with this, would I need to split this newly created Matrix into two, so that I have a 4 x 4 with all rows where the Class is 0 and another 4 x 4 with all rows where the Class is 1?
And then I would just do the means of the Pixel Density column?
Sorry for the trouble, I am mostly trying to understand the problem itself and not necessarily struggling with syntax.
Upvotes: 3
Views: 62
Reputation: 104504
The best thing to do would be to use accumarray
as this naturally places numbers into the same group. For example, we would place the first four values for the pixel density into group 0, and the next four into group 1. You then apply some operation on the values that belong to each group. In this case, you want to apply the mean.
The only intricacy is that MATLAB starts indexing at 1, so you need to offset the first column of your text file, the group number by 1.
Therefore, it's very simply this code:
% Your code
testFile = fopen('test_file.txt', 'r');
sizeOfTestFile = [4 Inf];
testFileMatrix = fscanf(testFile, '%d', sizeOfTestFile);
testFileMatrix = testFileMatrix';
% Calculate the average of each group
means = accumarray(testFileMatrix(:, 1) + 1, testFileMatrix(:, 4), [], @mean);
We thus get:
>> means
means =
40
250
Obviously, the mean of each group is 40 and 250 respectively because each group only consists of 40 and 250.
If you're confused with accumarray
, one thing you can do is look at all unique group values, loop through them and isolate out the pixel densities that belong to the group and find the average.
Something like this would work:
means = [];
for i = 1 : max(testFileMatrix(:, 1)) + 1
means(end + 1) = mean(testFileMatrix(testFileMatrix(:, 1) + 1 == i, 4));
end
This would iteratively add the mean of each group to the means
vector until you reach all of the groups. This of course is a slower alternative, but it does do what you want in a more intuitive way if you're not comfortable with accumarray
.
Upvotes: 5