How to open and modify .dat file
Réponse acceptée
Plus de réponses (2)
- Open the file for binary read access using the 'fopen' function
- Read the data using the 'fread' function to read data from binary file
1 commentaire
0 votes
Hi @mohd akmal masud,
Since your data is in an 8-bit integer format, you can use the `fopen`, `fread`, and `reshape` functions. First start by specifying the name of the file you wish to read. Ensure that the file is in the current directory or provide the full path.
filename = 'your_file.dat'; % Replace with your actual file name
Now, use the fopen function to open the file in read mode. This function returns a file identifier (fid) that you will use for subsequent operations.
fid = fopen(filename, 'r');
For successful file opening, it is crucial to verify that the file has been opened successfully. If fid equals -1, it indicates an error in opening the file. In such a case, you should handle the error appropriately.
if fid == -1
error('File cannot be opened. Check the filename or path.');end
Now, the fread function to read the data from the file, you can use fread function. As you can see that the data is read as unsigned 8-bit integers and is structured to read a total of 364 rows and 364*110 columns.
data = fread(fid, [364, 364*110], 'uint8'); % Read as unsigned 8-bit integers
After reading the data, it is good practice to close the file using the fclose function to free up system resources.
fclose(fid);
Finally, reshape the one-dimensional array data into a three-dimensional array. The dimensions specified in the reshape function correspond to the original structure of the data.
data_3D = reshape(data, [364, 364, 110]);
To modify aspects of the geometry represented by your data (assuming you want to change dimensions or values), here are some common operations:
If you want to resize your array, you can use interpolation methods such as `imresize` from the Image Processing Toolbox:
% Define your new dimensions
new_size = [new_rows, new_cols, new_slices];
resized_data = imresize3(data_3D, new_size);
To modify specific values based on certain conditions (e.g., thresholding), you can do so using logical indexing:
% Example: Set all values below a threshold to zero
threshold = 50; % Define your threshold value
data_3D(data_3D < threshold) = 0;
Try to visualize changes made to your geometry or data structure by considering using slice or volume visualization functions:
slice(data_3D, [], [], [1:110]); % Visualize slices along the third dimension
Let me share some tips, when modifying data arrays, please make sure that any changes maintain the integrity of the original dataset unless intentional alterations are required for analysis. Always refer to MATLAB’s official documentation for detailed explanations of functions and their parameters. This will enhance your understanding of how each function operates and most importantly before making any modifications, it's wise to create a backup of your original data to prevent accidental loss. Also, for more information about functions used in this code, please click the names of functions.
Hope this helps. Please let me know if you have any further questions.
9 commentaires
Hi @mohd akmal masud,
To address your query regarding, “But what I want is, is it possible I change the shape perimeter is circle? instead of semi circle as already picture attached. If possible, where is the data I should modify?”
Please see my response to your comments below.
So, @Stephen23 already provided an example that shows successfully loading your binary file (`nema.dat`) and reshaped it into a 3D array with dimensions [364, 364, 110] which shows a semi-circular representation of this data. So, in order create a circular representation of your data, you have to modify his code by utilizing polar coordinates to map the data points onto a circle.
So right after @Stephen’s 23 line of code, arr = reshape(arr,dim), add the following lines of code to accomplish your task.
% Define parameters for circular representation
theta = linspace(0, 2*pi, size(arr, 1)); % Angular coordinates for full circle
r = linspace(0, 1, size(arr, 2)); % Radial coordinates (normalized)
% Create meshgrid for circular coordinates
[R, T] = meshgrid(r, theta);
[X, Y] = pol2cart(T, R); % Convert polar to Cartesian coordinates
% Initialize figure for plotting
figure;
hold on;
% Loop through each layer of your data (third dimension)
for k = 1:size(arr, 3)
% Use scatter or surface plot to visualize data in circular form
scatter(X(:), Y(:), 10, arr(:,:,k), 'filled'); % Adjust size as needed
end
% Set equal aspect ratio to maintain circular shape
axis equal;
title('Circular Representation of Data'); xlabel('X-axis'); ylabel('Y-axis');colorbar; % Optional: Show color scale corresponding to data values
hold off;
So, in code, theta variable spans from 0 to 2πfull circle while rspans from 0 to 1 allows you to represent all points in a circular format. Then, pol2cart function converts polar coordinates (R and T) into Cartesian coordinates (X and Y) suitable for plotting.The loop iterates through each layer of @Stephen23 reshaped array (`arr`), creating scatter plots for each layer. If you want, adjust the marker size in the `scatter` function as necessary for better visibility. Hope this helps, please let me know if you have any further questions.
Hi @ mohd akmal masud,
Sorry, I couldn’t open your .dat file in matlab mobile. So, I end up creating output.dat file based on your comments mentioned above, “According to the manual, the description of my file is 364 × 364 × 110, integer, 8-bit.” However, the data size was huge but I was able to replicate the error as shown below.


So, this error encountered with the scatter function arises because the color input must be formatted correctly. In my code, arr(:,:,k) is likely a 2D array, which does not match the expected dimensions for the color input in scatter. So, to resolve this, you can modify the code to ensure that the color data is reshaped appropriately. Here’s a revised version of the plotting section:
% Loop through each layer of your data (third dimension)
for k = 1:size(arr, 3)
% Reshape the color data to match the number of points
colorData = reshape(arr(:,:,k), [], 1);
% Use reshaped color data
scatter(X(:), Y(:), 10, colorData, 'filled');
end
So, in this code, you will see that based on adjustment made, it will reshape arr(:,:,k) into a column vector to make sure that it will match the number of points in X and Y which should eliminate the error and allow for a successful circular representation of your data. Please let me know if this helped resolve your issue.
Hi @mohd akmal masud,
Addressing your query, “Form the original data, the perimeter is semicircle with index 9 as the red arrow show. Then I want to transform it into full circle with same index 9 as the new data set picture I want.From the original data, the inside background is 7 as the red arrow show. Then I want to transform into full uniform background with same index 7 as new data Picture show.Then if you can see in the new data set picture I want, all the blob in the original data I want to remove.But the dimension of the new data set picture I want is same with original data 364x364x100,can you understand me? “
Please see my response to your comments below.
Since I am using matlab mobile, I could not load your file “nema.dat” to troubleshoot the problem. The one I created doesn’t exactly match your data output but it was created to troubleshoot the error, “Error using scatter Color must be one RGB triplet, an m-by-3 matrix of RGB triplets with one color per scatter point,or an m-by-1 vector with one value per scatter point.” However, I was able to fix error but now based on your recent comments and clarification of new requirements, I will illustrate solution using example code snippet which you can modify based on your requirements. This code has already been executed step by step about what you mentioned in your comments.
So first, I defined the parameters for the transformation, including the dimensions of the dataset and the indices for the semicircle and background based on your comments.
% Define parameters
originalDimensions = [364, 364, 100]; % Dimensions of the original dataset
semicircleIndex = 9; % Index for the semicircle
backgroundIndex = 7; % Index for the background
newData = zeros(originalDimensions); % Initialize new data array
To create a full circle from the semicircle, I use the meshgrid function to generate a grid of coordinates and then apply the equation of a circle.
% Create a grid of coordinates
[x, y] = meshgrid(1:originalDimensions(1), 1:originalDimensions(2));
radius = originalDimensions(1) / 4; % Define the radius of the circle
% Center of the circle
center = [originalDimensions(1)/2, originalDimensions(2)/2];
% Create a full circle mask
circleMask = (sqrt((x - center(1)).^2 + (y - center(2)).^2) <= radius);
Next, I set the background of the new dataset to a uniform value, replacing the original background index.
% Set the background to a uniform value
% Assign semicircle index to the circle area
newData(circleMask) = semicircleIndex;
% Assign background index to the rest
newData(~circleMask) = backgroundIndex;
Then, removing blobs from the original dataset, I use morphological operation by using bwareaopen function which can be particularly useful for this purpose.
% Assuming originalData is the input dataset
originalData = rand(originalDimensions); % Placeholder for original data
% Create a binary image for the semicircle
binaryImage = originalData == semicircleIndex;
% Remove blobs
cleanedImage = bwareaopen(binaryImage, 50); % Remove small objects
Finally, combine the cleaned image with the new background and circle.
% Combine cleaned image with new data
newData(cleanedImage) = 0; % Set the cleaned blobs to zero in the new data
To visualize the final result, I used the imshow function to display a slice of the 3D dataset.
% Plot the final result
figure;
imshow(newData(:, :, 1), []); % Display the first slice of the new dataset
title('Transformed Dataset');
colormap(gray); % Set colormap to gray for better visibility
Please see attached.


If you still have any further questions, please let me know.
Hi @mohd akmal masud,
You are absolutely right. I was trying to demonstrate an example because of the size of data being too large. So, that is the reason that only the first slice appears when using imshow(newData(:, :, 1), []). Also, when you specify just one slice (the first one), it displays that slice alone, ignoring others in the 3D array. So, to help you visualize all slices of your transformed dataset effectively, consider using a loop or employing MATLAB’s slice function which can handle 3D data better. For more information regarding this function, please refer to
Here’s how you can modify visualization code:
% Visualize all slices in a loop
figure;
for i = 1:originalDimensions(3)
subplot(10, 10, i); % Adjust subplot grid size according to number of slices
imshow(newData(:, :, i), []);
title(['Slice ' num2str(i)]);
colormap(gray); % Set colormap to gray for better visibility
end
Alternatively, if you want an interactive way to view slices:
% Using slice function for better 3D visualization
figure;
slice(newData, [], [], 1:originalDimensions(3));
colormap(gray);
title('Transformed Dataset - All Slices');
Hope this helps. If you have any more questions or require further clarification on any specific aspect of your project, feel free to ask!
Catégories
En savoir plus sur Blocked Images dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!






