Very simple code of adding two matrices horizontally retyrns an error using horzcat, dimensions of arrays being concatenated are not consistent. the error is on line (theta = [theta(:,1:6),zeros(length(theta),1)];).
the excel file has a matrix of 4x6, which i check with size theta even.
the code is:
clear all
clc
% Input:
tmp = importdata ('exp.xlsx');
theta = tmp.data;
theta = [theta(:,1:6),zeros(length(theta),1)];
% Calcu
theta (:,7) = theta (:,2).*theta(:,3);
%output
file_name = 'total.txt';
fid = fopen(file_name,'w');
fprintf(fid,'This file is written by matlab code.\n\n');
fprintf(fid,'This code will calculate the total.\n\n');
for i = 1:length(theta)
fprintf(fid,'The total of %d with age %f and exp %f is %f.\n',theta(i,1),theta(i,2),theta(i,3),theta(i,4));
end
fprintf(fid,'\nENDFILE');
fclose (fid);

 採用された回答

VBBV
VBBV 2023 年 6 月 14 日
編集済み: VBBV 2023 年 6 月 14 日

0 投票

theta = [theta(:,1:6),zeros(size(theta,1),1)];

4 件のコメント

VBBV
VBBV 2023 年 6 月 14 日
Preallocate the matrix theta with correct number of zeros
rida
rida 2023 年 6 月 14 日
THANKS, ERROR RESOLVED. what exactly happened here? it worked when i only had 3 columns
Steven Lord
Steven Lord 2023 年 6 月 14 日
The length function on a non-empty array returns the size in the longest dimension of your array. That's not necessarily the number of rows.
A = ones(3, 6);
length(A)
ans = 6
Calling size with 1 as the dimension input will give you the number of rows in the array.
size(A, 1)
ans = 3
rida
rida 2023 年 6 月 14 日
thanks, this was very helpful. much thanks

サインインしてコメントする。

その他の回答 (1 件)

Satwik
Satwik 2023 年 6 月 14 日

0 投票

You can make the following change if your goal is to concatenate.
tmp = zeros(4,6);
theta = tmp;
theta = [theta(:,1:6),zeros(size(theta,1),1)]
theta = 4×7
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

カテゴリ

製品

リリース

R2019a

タグ

質問済み:

2023 年 6 月 14 日

コメント済み:

2023 年 6 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by