How to reshape data in 4-D array correctly?

7 次查看(过去 30 天)
For debugging purposes, I've loaded the following table data into my MATLAB script, I want to arrange my table data into a 4-d array. x, y, z, w are my independent variables, and v is my dependent variable.
I want to be able to access the data in v through my 4d array in the following fashion: v_reshaped(1,1,1,1) = 1, v_reshaped(1,1,1,2) = 2, v_reshaped(1,1,2,1) = 3
However, with the script I've written, the data appears as follows: v_reshaped(1,1,1,1) = 1, v_reshaped(1,1,1,2) = 9, v_reshaped(1,1,2,1) = 5
I've put my MATLAB script here for reference, can you show me how I can get the reshaped data in the order I want?
Below is an image of my table:
I've written the following MATLAB script:
% Clear everything
clear all; close all;
% Read table from MATLAB
btable = readtable('binary_lut_test.xlsx');
x.val = btable.x; y.val = btable.y;
z.val = btable.z; w.val = btable.w;
v.val = btable.v;
% Unique values from table
x.uni = unique(x.val); y.uni = unique(y.val);
z.uni = unique(z.val); w.uni = unique(w.val);
v.uni = unique(v.val);
% Create and n-dimensional grid
[X, Y, Z, W] = ndgrid(x.uni, y.uni, z.uni, w.uni)
% Compute expected number of elements
expectedNumel = numel(x.uni) * numel(y.uni) ...
* numel(z.uni) * numel(w.uni); % Evaluates
% to 16
% Reshape data
V.a = reshape(v.val, [numel(x.uni), numel(y.uni),...
numel(z.uni), numel(w.uni)]);

回答(1 个)

Stephen23
Stephen23 2023-11-27
编辑:Stephen23 2023-11-27
You can use PERMUTE like this:
v = 1:16;
z = permute(reshape(v,[2,2,2,2]),[4,3,2,1]);
z(1,1,1,1)
ans = 1
z(1,1,1,2)
ans = 2
z(1,1,2,1)
ans = 3

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by